MongoDB Embedded Documents and Arrays, With Query Examples
For MongoDB beginners who can insert and find documents, and want to store and query data nested inside them.
On this page
MongoDB can store a document inside a field of another document, as an embedded document. An array field holds a list of values, or a list of embedded documents. For example, a passenger document can hold its address as an embedded document and its bags as an array.
A relational database would keep the bags in a second table and join it back. In MongoDB, one read returns the passenger with all the bags.
A document can hold embedded documents and arrays in any combination:
{
field: value,
document: { field: value, field: value },
values: [ value, value ],
documents: [ { field: value }, { field: value } ]
}
documentis an embedded document, with fields of its own.valuesis an array of values, such as strings or numbers.documentsis an array of embedded documents.- A path such as
"document.field"names an inner field. A number in the path picks an array element by its position, counting from 0:"values.0".
Create a passengers collection with three passengers:
db.passengers.insertMany([
{
name: "Alice",
address: { city: "Paris", country: "FR" },
flights: ["AF12", "AF15"],
bags: [{ item: "backpack", kg: 8 }, { item: "trolley", kg: 18 }]
},
{
name: "Bob",
address: { city: "Lyon", country: "FR" },
flights: ["AF15"],
bags: [{ item: "duffel", kg: 10 }]
},
{
name: "Carol",
address: { city: "Boston", country: "US" },
flights: ["DL40", "AF12"],
bags: [{ item: "backpack", kg: 8 }, { item: "suitcase", kg: 25 }]
}
])
Each dot in a path goes one level down:
The second argument of each find is a projection. It picks the fields to print in mongosh, the MongoDB shell: 1 shows a field, and 0 hides it.
Dot notation
Dot notation names a field inside an embedded document. For example, you can find the passengers whose address has the country FR.
db.passengers.find({ "address.country": "FR" }, { _id: 0, name: 1, address: 1 })
The query returns Alice and Bob, each with the whole address. Their addresses have the country FR, and Carol's has US.
Write the path in quotes. A name with a dot in it is not a valid JavaScript name.
Arrays of values
A condition on an array field matches a document when at least one element equals the value. For example, you can find the passengers who have AF12 in their flights.
db.passengers.find({ flights: "AF12" }, { _id: 0, name: 1, flights: 1 })
The query returns Alice and Carol. AF12 is Alice's first flight and Carol's second. Bob has only AF15.
Arrays of embedded documents
Dot notation also works on an array of embedded documents: "bags.item" names the item field of the bags. For example, you can find the passengers who carry a backpack.
db.passengers.find({ "bags.item": "backpack" }, { _id: 0, name: 1, "bags.item": 1 })
The query returns Alice and Carol. Each has a backpack, and one matching element is enough.
Alice and Carol come back with the item of every bag, the trolley and the suitcase included. The projection returns every element of the bags array.
$elemMatch
$elemMatch matches a document only when a single element of an array meets all the conditions. For example, you can find the passengers with a bag heavier than 10 kg and lighter than 20 kg.
Run the query without $elemMatch first:
db.passengers.find({ "bags.kg": { $gt: 10, $lt: 20 } }, { _id: 0, name: 1 })
The first query returns Alice and Carol. Carol's suitcase weighs 25, which is over 10, and her backpack weighs 8, which is under 20. Each condition is met by a different bag.
Now put the same two conditions inside $elemMatch:
db.passengers.find({ bags: { $elemMatch: { kg: { $gt: 10, $lt: 20 } } } }, { _id: 0, name: 1 })
The second query returns Alice alone. Her trolley weighs 18, so one bag meets both conditions. Carol has no such bag.
$push
$push adds an element to the end of an array. For example, you can add a pair of skis to Bob's bags.
db.passengers.updateOne({ name: "Bob" }, { $push: { bags: { item: "skis", kg: 12 } } })
db.passengers.find({ name: "Bob" }, { _id: 0, name: 1, bags: 1 })
The find prints:
[
{
name: 'Bob',
bags: [ { item: 'duffel', kg: 10 }, { item: 'skis', kg: 12 } ]
}
]
The update changed Bob's document only. To remove elements, use $pull: { $pull: { bags: { item: "skis" } } } removes every bag with the item skis.
The positional $ operator
The positional $ in an update path stands for the array element that matched the filter, the first one if several matched. The filter is the first argument of updateOne. For example, you can change the weight of Carol's suitcase without knowing its position.
db.passengers.updateOne(
{ name: "Carol", "bags.item": "suitcase" },
{ $set: { "bags.$.kg": 23 } }
)
db.passengers.find({ name: "Carol" }, { _id: 0, name: 1, bags: 1 })
The find prints:
[
{
name: 'Carol',
bags: [ { item: 'backpack', kg: 8 }, { item: 'suitcase', kg: 23 } ]
}
]
The filter matched the suitcase, Carol's second bag. So bags.$.kg is the suitcase's weight, and $set changed that weight from 25 to 23.
What goes wrong
A whole embedded document in a query
A query can match a whole embedded document instead of one field. The query must then list the same fields in the same order as the stored document:
db.passengers.find({ address: { city: "Paris", country: "FR" } }, { _id: 0, name: 1 })
The query returns Alice, the only passenger whose address is exactly that document. Swap the two fields to { country: "FR", city: "Paris" }, and the query returns no document.
To match the fields in any order, use dot notation on each field: { "address.city": "Paris", "address.country": "FR" }.
Two arrays in one index
An index on an array field is a multikey index: it holds one entry for each distinct value in the array. A compound index is an index on several fields. In one document, at most one field of a compound index can hold an array:
db.passengers.createIndex({ flights: 1, "bags.item": 1 })
Both flights and bags are arrays, so MongoDB refuses the index. The error says "cannot index parallel arrays" and names the two fields. Index each array on its own instead, such as { "bags.item": 1 }.
Embed or reference
Embed small data that belongs to one parent document and is read with the parent, such as an address or a few bags. If many documents share the data, or the data keeps growing, put it in its own collection. A document can't exceed 16 mebibytes.
For more on this choice, read the next lesson, embed versus reference.
Embedded documents and arrays on a DbSchema diagram
DbSchema connects to MongoDB and draws each collection on a diagram. DbSchema infers the fields and their types from a sample: by default, the first 100 and the last 100 documents of each collection.
The diagram above is the shop database from DbSchema's documentation. Each customer has a nested address, and each order has an items array. DbSchema shows the passengers collection the same way: address as an object, and bags as an array of objects.
The fields on the diagram approximate the sampled documents, and MongoDB enforces none of them. A validator is a set of rules that MongoDB checks on every write. For a collection without a validator, the Edit Collection dialog shows Inferred ( no validation ).
If a collection has a $jsonSchema validator, DbSchema reads the fields from the validator instead of the sample. Editing the collection in DbSchema writes the validator to the database and to the model file, where DbSchema saves your design.
A virtual relation links two collections in the model file only. You draw one by dragging one field onto another. The Data Explorer follows virtual relations from a document to its related documents, level after level.
The HTML5 documentation shows the diagram as a vector image, with collection and field comments as mouse-over tooltips.
Download DbSchema at https://dbschema.com/download.html, connect it to your MongoDB database, and open your collections on the diagram. Connecting to MongoDB and the diagram are in the free Community Edition. The Data Explorer across relations and the HTML5 documentation are in DbSchema Pro.
See your MongoDB collections as a diagram
DbSchema connects to MongoDB, infers the fields from a sample of documents, and shows embedded documents and arrays as nested fields on the diagram. Connecting and the diagram are in the free Community Edition.