low-json-db

Working with Collections

A collection is the equivalent of a table in a relational database or a collection in MongoDB. In low-json-db, each collection is stored as a single JSON file on disk.

Creating a Collection

You can create (or open) a collection in two ways: by passing a simple string, or by passing a configuration object.

Simple style

const users = db.collection('users');

With options (recommended)

const users = db.collection({
  name: 'users',
  autoId: true,                // automatically generate _id
  idType: 'auto',              // 'auto' | 'uuid' | 'objectid'
  indexes: ['email', 'city'],  // fields to index
  pretty: true                 // pretty-print the JSON file
});
Important: The collection is created lazily. The actual .json file is only written when you insert the first document.

What happens on disk?

When you use a collection named users, the library manages these files:

Listing Collections

const names = db.listCollections();
console.log(names); // ['users', 'products', 'orders']

Dropping a Collection

This permanently deletes the collection file and its index file.

const deleted = db.dropCollection('users');
console.log(deleted); // true if it existed, false otherwise

Unloading from Memory

If you are working with many large collections, you can free memory by unloading a collection that you no longer need:

db.unloadCollection('users');

The next time you call db.collection('users'), it will be loaded again from disk.

Best Practices

Next: Learn how to insert documents.