Documents and collections in NoSQL
Topic 2 of 34 · 8 minFree lessonIn 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.
db.getCollectionNames()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.
db.books.countDocuments()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.
db.authors.findOne({ name: "Chinua Achebe" })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.
db.customers.findOne({ name: "Ana Silva" })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.
db.orders.findOne({ _id: 101 })A document inside another one is called an embedded document. Keeping related data together like this is what document databases do best.
Title and title are different fields. No book has a Title field, so nothing matches.db.books.findOne({ Title: "Dune" })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.