Documents & Collections
A document is one record made of fields, and a collection is a group of documents, like a table of records.
In this page:
Syntax
db.collection_name.insertOne({
field: "value",
nested: { key: value },
list: [value1, value2]
})
Documents & Collections
Documents are field-value pairs that can hold strings, numbers, booleans, dates, arrays and nested documents. A collection groups related documents and is created automatically on first insert.
Documents in the same collection do not have to share the same fields.
Note:
Collections are schemaless by default, but you can add validation rules.
Example: Documents & Collections
test> db.people.insertMany([
... { _id: 1, name: "Ada", address: { city: "London", zip: "N1" }, skills: ["math", "code"] },
... { _id: 2, name: "Linus", email: "[email protected]" }
... ])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2 } }
test> db.people.find()
[
{
_id: 1,
name: 'Ada',
address: { city: 'London', zip: 'N1' },
skills: [ 'math', 'code' ]
},
{ _id: 2, name: 'Linus', email: '[email protected]' }
]
test> db.people.findOne({ "address.city": "London" }, { name: 1, "address.zip": 1 })
{ _id: 1, name: 'Ada', address: { zip: 'N1' } }
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Expecting all documents to have identical fields
- Creating one giant collection for everything
- Forgetting collection names are case sensitive
Chapter Summary
- A document is a set of fields and values
- Values can be arrays and nested documents
- A collection groups documents
- Collections are created on first insert
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: