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
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:
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:
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
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.Ordersanddb.ordersare 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 exampledb.getCollection('order-items').
db.getCollection('order-items').insertOne({ _id: 1, sku: 'A1' });
print(db.getCollection('order-items').countDocuments());1
Test yourself
When do you need db.createCollection()?
- Always, before the first insert
- Only when the collection needs options such as a validator or capped size
- Only for collections with more than 1000 documents
- Never; it is deprecated
A capped collection with max: 3 holds 3 documents and you insert a 4th. What happens?
- An error is thrown
- The insert is ignored
- The oldest document is removed
- The collection grows to 4
What is the difference between drop() and deleteMany({})?
- There is none
- drop() also removes the indexes and options; deleteMany({}) only removes documents
- deleteMany({}) is faster than drop()
- drop() keeps the documents