Documents Inside Documents
A field can hold a whole document. This course also has a products collection. Each product keeps its technical details in a nested specs document:
db.products.findOne({ _id: 1 })
Output:
{ _id: 1, name: 'Laptop', specs: { ram: 16, storage: 512 } }
The specs belong to the product, so they are stored inside the product. You do not need a second collection for them.
To reach a field inside a nested document, use dot notation. "specs.storage" means "the storage field inside specs". Put it in quotes, because of the dot:
db.products.find(
{ "specs.storage": 256 },
{ _id: 0, name: 1 }
)
Output:
[ { name: 'Phone' } ]
Updates use dot notation in the same way:
db.products.updateOne(
{ _id: 2 },
{ $set: { "specs.ram": 12 } }
)
db.products.findOne({ _id: 2 }, { _id: 0, specs: 1 })
Output:
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
{ specs: { ram: 12, storage: 256 } }
Only specs.ram changed. specs.storage is still 256. Without the dot, { $set: { specs: { ram: 12 } } } would replace the whole specs document, and storage would be lost. This is a common mistake, so remember the dot.
Nesting can go many levels deep. "a.b.c" reaches three levels in. Put fields in a nested document when they belong together, like the specs of one product.
In the exercise, find the products with 16 GB of RAM or more.