0PricingLogin
MongoDB Academy · Lesson

Querying Nested Fields and Arrays

Learners will write dot-notation queries to reach into embedded sub-documents and individual array elements.

Why Nested Queries Matter

One of MongoDB's signature strengths is storing nested sub-documents and arrays inside a document. But this power is only useful if you can also query that nested data efficiently. MongoDB's dot notation lets you reach into any depth of nesting to filter, project, index, and update specific fields.

Without this capability, you would have to load entire documents into your application and filter in code—wasting bandwidth and making indexes useless. Dot notation queries run server-side, benefiting from indexes on nested fields.

Dot Notation for Nested Fields

Dot notation uses a period (.) to navigate into nested sub-documents. The query { 'address.city': 'Chicago' } matches documents where the address field is an object with a city field equal to 'Chicago'. You can chain dots to any depth: 'address.location.lat'.

The key rule: always wrap dot-notation paths in quotes when used as object keys in JavaScript (because the dot would otherwise be parsed as property access). This is a frequent beginner mistake.

// Document structure
// { name: 'Alice', address: { city: 'Chicago', state: 'IL' } }

// Correct: dot notation in quotes
db.users.find({ 'address.city': 'Chicago' });

// Incorrect: this queries for a field literally named 'address.city'
// (a common mistake)
db.users.find({ address: { city: 'Chicago' } });
// This requires the address to be EXACTLY { city: 'Chicago' } — no other fields!

// Deep nesting: 3 levels
db.users.find({ 'address.location.lat': { $gt: 41.5 } });

All lessons in this course

  1. insertOne and insertMany
  2. findOne vs find: Cursors Explained
  3. Querying Nested Fields and Arrays
  4. Reading Documents With the Node.js Driver
← Back to MongoDB Academy