TExcelTAD
Home › MongoDB › MongoDB Collections

MongoDB Collections

A collection is a group of documents, the MongoDB counterpart of a table. Like databases, collections are usually created implicitly: the first insert into db.reviews creates the reviews collection.

Implicit creation

mongosh · try it yourself
print(db.getCollectionNames().sort());
db.reviews.insertOne({ _id: 1, productId: 3, stars: 5, text: 'Bright and fruity.' });
print(db.getCollectionNames().sort());
[ 'customers', 'orders', 'products' ]
[ 'customers', 'orders', 'products', 'reviews' ]

Note: getCollectionNames() doesn't promise any particular order, so the examples sort the list before printing it.

Explicit creation with createCollection

db.createCollection(name, options) creates a collection up front. You need it when the collection should have special options:

Option Effect
validator rules every document must satisfy (Schema Validation)
capped: true, size, max a fixed-size collection that overwrites its oldest documents
timeseries storage optimised for measurements over time
collation default language rules for string comparison and sorting
clusteredIndex stores documents ordered by _id

A capped collection behaves like a ring buffer. This one keeps only the 3 newest log entries:

mongosh · try it yourself
print(db.createCollection('recent_logins', { capped: true, size: 4096, max: 3 }));
for (const user of ['ada', 'alan', 'grace', 'linus', 'hedy']) {
  db.recent_logins.insertOne({ _id: user });
}
print(db.recent_logins.find().toArray());
print(db.recent_logins.isCapped());
{ ok: 1 }
[ { _id: 'grace' }, { _id: 'linus' }, { _id: 'hedy' } ]
true

The two oldest documents (ada, alan) were dropped automatically to make room.

Inspecting collections

db.getCollectionInfos() returns each collection's name, type and options. Here we look at just the interesting parts:

mongosh · try it yourself
db.createCollection('events', { capped: true, size: 8192 });
for (const info of db.getCollectionInfos({ name: { $in: ['events', 'orders'] } })) {
  print(info.name, info.type, info.options);
}
print(db.orders.countDocuments(), 'orders');
print(db.orders.estimatedDocumentCount(), 'orders (estimated)');
events collection { capped: true, size: 8192 }
orders collection {}
20 orders
20 orders (estimated)

countDocuments() counts exactly and accepts a filter; estimatedDocumentCount() reads the collection's metadata instead, which is instant even for billions of documents but takes no filter.

Renaming and dropping

mongosh · try it yourself
db.products.renameCollection('catalog');
print(db.getCollectionNames().sort());

print('dropped:', db.catalog.drop());
print(db.getCollectionNames().sort());
[ 'catalog', 'customers', 'orders' ]
dropped: true
[ 'customers', 'orders' ]

drop() deletes the collection, its documents and its indexes. To empty a collection but keep its indexes and options, use deleteMany({}) instead.

Naming collections

  • Names are case-sensitive: db.Orders and db.orders are different collections.
  • Don't start with system. (reserved) and avoid $ and the empty string.
  • If a name clashes with a shell method or contains special characters, use db.getCollection('name'), for example db.getCollection('order-items').
mongosh · try it yourself
db.getCollection('order-items').insertOne({ _id: 1, sku: 'A1' });
print(db.getCollection('order-items').countDocuments());
1

Test yourself

When do you need db.createCollection()?

  1. Always, before the first insert
  2. Only when the collection needs options such as a validator or capped size
  3. Only for collections with more than 1000 documents
  4. Never; it is deprecated

A capped collection with max: 3 holds 3 documents and you insert a 4th. What happens?

  1. An error is thrown
  2. The insert is ignored
  3. The oldest document is removed
  4. The collection grows to 4

What is the difference between drop() and deleteMany({})?

  1. There is none
  2. drop() also removes the indexes and options; deleteMany({}) only removes documents
  3. deleteMany({}) is faster than drop()
  4. drop() keeps the documents