Skip to main content
MongoDB
CHAPTER 17 Beginner

MongoDB Array Queries | Dot Notation & Positional Operator

Updated: May 16, 2026
15 min read

# CHAPTER 17

Working with Arrays and Nested Documents

1. Introduction

Because MongoDB abandons strict SQL tables in favor of dynamic BSON documents, a massive amount of your data will be deeply nested inside Objects and Arrays. How do you find a user whose city is "London" when city is buried inside an address object? How do you update the 3rd item in a comments array without deleting the other 20 comments? In this chapter, we will master Dot Notation and the Positional Operator to surgically interact with nested data.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Query Embedded Documents using Dot Notation.
  • Search for specific items inside an Array.
  • Push and Pull items to/from an Array.
  • Update a specific element inside an Array using the Positional Operator ($).

3. Querying Embedded Objects (Dot Notation)

Suppose you have a document: { name: "John", address: { city: "London", zip: "10001" } }. You cannot query { address: "London" } because address is an object, not a string! To look inside an object, MongoDB uses Dot Notation.
javascript
12345
// CRITICAL: When using dot notation in a query, you MUST wrap the key in quotes!
db.users.find({ "address.city": "London" })

// Digging deeper: Find users with a specific zip code inside their office address
db.users.find({ "contact_info.office.address.zip": "10001" })

4. Querying Arrays

If you have an array of simple strings: { tags: ["news", "sports", "tech"] }. MongoDB is incredibly smart. You don't need dot notation. You just query the field directly!
javascript
12
// This magically searches INSIDE the array and returns the document if 'tech' is present!
db.articles.find({ tags: "tech" })

5. Modifying Arrays ($push and $pull)

In SQL, adding a "Tag" requires inserting a new row into a pivot table. In MongoDB, you simply append it to the Array using the $push update operator.
javascript
1234567891011
// Add a new tag to the article
db.articles.updateOne(
    { _id: 1 },
    { $push: { tags: "coding" } } // Appends 'coding' to the end of the array!
)

// Remove a specific tag from the article
db.articles.updateOne(
    { _id: 1 },
    { $pull: { tags: "sports" } } // Deletes 'sports' from the array!
)

6. Updating an Array of Objects (The Positional Operator $)

This is the hardest concept in MongoDB updates. Imagine a Blog Post document with an array of Comments:
json
1234567
{
  "_id": 1,
  "comments": [
    { "user": "Alice", "likes": 5 },
    { "user": "Bob", "likes": 2 }
  ]
}

A user clicks "Like" on Bob's comment. We need to increment Bob's likes to 3. But how do we tell MongoDB *which* comment to update? We don't know the index (is it comments[0] or comments[1])?

We use the Positional Operator ($). The $ acts as a placeholder. It tells MongoDB: "Hey, remember the item that matched my filter? Use its index!"

javascript
1234567
db.posts.updateOne(
    // 1. The Filter: Find Post #1, AND find the exact comment made by Bob.
    { _id: 1, "comments.user": "Bob" },
    
    // 2. The Update: Use the '$' placeholder to increment THAT specific comment!
    { $inc: { "comments.$.likes": 1 } } 
)

*(MongoDB finds Bob at index 1, so "comments.$.likes" dynamically becomes "comments.1.likes" behind the scenes!)*

7. Mini Project: The Shopping Cart

Let's build the backend logic for an E-Commerce cart.
javascript
1234567891011121314151617
// 1. Add an Item to the Cart ($push)
db.carts.updateOne(
    { user_id: 123 },
    { $push: { items: { name: "Mouse", qty: 1, price: 20 } } }
)

// 2. The user changes the quantity of the "Mouse" to 5 (Positional Operator $)
db.carts.updateOne(
    { user_id: 123, "items.name": "Mouse" },
    { $set: { "items.$.qty": 5 } }
)

// 3. The user removes the Mouse from the cart entirely ($pull)
db.carts.updateOne(
    { user_id: 123 },
    { $pull: { items: { name: "Mouse" } } }
)

8. Common Mistakes

  • Forgetting Quotes in Dot Notation: Typing db.users.find({ address.city: "London" }) will throw a fatal Javascript syntax error. Object keys with dots in them must be encapsulated in string quotes: "address.city".
  • Using $set to add Array items: If you use $set: { tags: "coding" }, it will delete the entire array and replace it with the single string "coding". You must use $push to append to an array.

9. Best Practices

  • Limit Array Growth: As discussed in Chapter 13, arrays should not grow infinitely. If a $push operation is running 1,000 times a day on a single document, you are architecting the database wrong. Move that data to a separate collection.

10. Exercises

  1. 1. What update operator is used to remove a specific item from an Array?
  1. 2. Why is the Positional Operator ($) required when updating an Array of Objects?

11. MongoDB Challenges

Write an updateOne() command that searches for an employee named "Sarah", and uses $push to add the string "MongoDB" to her skills array.
javascript
1234
db.employees.updateOne(
    { name: "Sarah" },
    { $push: { skills: "MongoDB" } }
)

12. MCQ Quiz with Answers

Question 1

When querying a deeply nested field inside an embedded document (e.g., finding the zip code inside the address object), what specific syntax MUST be used in MongoDB?

Question 2

When a document contains an Array of Objects, and you need to $set a value on one specific object without altering the others, what acts as the dynamic index placeholder in your update command?

13. Interview Questions

  • Q: Explain the mechanical difference between $push and $set when dealing with MongoDB arrays. What happens if you accidentally use $set on an array field?
  • Q: Describe a scenario where Dot Notation is required in a find() query, and explain why the key must be wrapped in quotes.

14. FAQs

Q: What if I want to update EVERY item in the array simultaneously? A: MongoDB introduced the "All Positional Operator" ($[]). If you run {$set: {"comments.$[].is_hidden": true}}, it will apply that update to every single object inside the array instantly!

15. Summary

Arrays and Nested Objects are the lifeblood of NoSQL architecture. By mastering Dot Notation to navigate deeply embedded data, utilizing $push and $pull for array manipulation, and wielding the Positional Operator ($) for surgical updates, you can maintain heavily denormalized documents with perfect precision.

16. Next Chapter Recommendation

Our dynamic schemas are incredibly flexible, but sometimes flexibility leads to chaos (like users accidentally typing their age as a string). In Chapter 18: Validation Rules and Data Integrity, we will learn how to enforce strict JSON Schema Validation to protect our database.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·