Introduction
Nested data stores information inside other information, like a box inside a bigger box. Querying nested data helps you find details deep inside your data quickly and easily.
Jump into concepts and practice - no test required
Nested data stores information inside other information, like a box inside a bigger box. Querying nested data helps you find details deep inside your data quickly and easily.
db.collection.find({ 'nested.field': value })db.users.find({ 'address.city': 'New York' })db.posts.find({ 'comments.author': 'Alice' })db.orders.find({ 'items.product': 'Book' })This example adds three users with nested address info. Then it finds users who live in New York by looking inside the nested address field.
db.users.insertMany([
{ name: 'John', address: { city: 'New York', zip: '10001' } },
{ name: 'Jane', address: { city: 'Boston', zip: '02101' } },
{ name: 'Mike', address: { city: 'New York', zip: '10002' } }
])
// Query users living in New York
db.users.find({ 'address.city': 'New York' })Remember to use quotes around nested field names with dot notation.
Querying nested data is powerful for complex documents but can be slower if indexes are missing.
Nested data stores information inside other information.
Use dot notation to query inside nested fields.
Querying nested data helps find detailed info quickly.
address.city equals "Paris"?{ "name": "Alice", "contact": { "email": "alice@example.com", "phone": "1234" } }, { "name": "Bob", "contact": { "email": "bob@example.com", "phone": "5678" } } What will the query db.collection.find({ "contact.email": "bob@example.com" }) return?db.users.find({ contact.phone: "1234" }). What is the main error here?{ "name": "Eve", "orders": [ { "id": 1, "item": "book" }, { "id": 2, "item": "pen" } ] } Which query finds documents where any order's item is "pen"?