← Back to MongoDB Course | Chapter 1: Introduction | Lesson 3 of 7

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:

  1. Documents & Collections
Syntax
javascript
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

bash
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
  1. Expecting all documents to have identical fields
  2. Creating one giant collection for everything
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.