CodeStride
Getting Started

Documents and collections in NoSQL

Topic 2 of 34 · 8 minFree lesson

In the last topic you met a single document. A database holds many of them, sorted into groups. This topic shows how MongoDB organizes them, and what a document can hold.

Databases, collections and documents

A MongoDB database holds collections: named groups of documents, like books or customers. A collection plays the part a table plays in SQL. db.getCollectionNames() lists them.

Example 1
db.getCollectionNames()
[ 'authors', 'books', 'customers', 'orders' ]

This bookstore has four collections. Each one holds documents about one kind of thing.

Counting documents

countDocuments() tells you how many documents a collection holds.

Example 2
db.books.countDocuments()
12

Every document has an _id

Every document has a field called _id, and no two documents in a collection can share the same one. It's how MongoDB tells documents apart, like a primary key in SQL. The books use numbers, but an _id can be text too, as the authors' are.

Example 3
db.authors.findOne({ name: "Chinua Achebe" })
{ _id: 'achebe', name: 'Chinua Achebe', born: 1930, country: 'Nigeria' }

If you add a document without an _id, MongoDB makes one for you. You'll see that in the next few topics.

What a field can hold

Fields hold different types of value: text (a string), numbers, true or false, and dates. A field can also hold a list (an array) or another document inside it. This customer's document shows several types at once.

Example 4
db.customers.findOne({ name: "Ana Silva" })
{ _id: 1, name: 'Ana Silva', email: 'ana@example.com', city: 'Lisbon', joined: ISODate('2024-02-11T00:00:00.000Z'), tags: [ 'regular' ]}

joined is a date, shown as ISODate(...), and tags is an array of strings. MongoDB keeps track of each value's type, so a date really is a date and a number really is a number.

Documents inside documents

An order keeps its items inside it: an array of small documents, one for each book bought. One order document holds everything about the order.

Example 5
db.orders.findOne({ _id: 101 })
{ _id: 101, customerId: 1, date: ISODate('2025-01-05T00:00:00.000Z'), status: 'delivered', items: [ { bookId: 1, title: 'Dune', qty: 1, price: 9.5 }, { bookId: 6, title: 'The Hobbit', qty: 1, price: 9 } ], total: 18.5}

A document inside another one is called an embedded document. Keeping related data together like this is what document databases do best.

Common mistakeGetting a field's name wrong. Field names care about capitals, so Title and title are different fields. No book has a Title field, so nothing matches.
Example 6
db.books.findOne({ Title: "Dune" })
null
TipName fields in camelCase, like customerId and publishedYear, and keep the same style everywhere. Many JavaScript apps read these documents, and that's their style too.

Try it yourself

Run the code in the editor and answer 8 practice questions on documents and collections. It's free, you only need an account.