Show List

Working with nested documents and arrays

In MongoDB, it's common to store nested documents and arrays within a document, which can help you represent more complex data structures. Here are some examples of how to work with nested documents and arrays in MongoDB:

  • Working with nested documents:
php
Copy code
db.users.insertOne({ name: "John", age: 30, email: "john@example.com", address: { street: "123 Main St", city: "Anytown", state: "CA", zip: "12345" } })

This creates a user document with a nested address document. You can query and update fields within the nested document using dot notation:

css
Copy code
db.users.find({"address.city": "Anytown"}) db.users.updateOne({name: "John"}, {$set: {"address.zip": "67890"}})
  • Working with arrays:
php
Copy code
db.users.insertOne({ name: "John", age: 30, email: "john@example.com", hobbies: ["reading", "cooking", "traveling"] })

This creates a user document with an array of hobbies. You can query and update array elements using the $ positional operator:

php
Copy code
db.users.find({hobbies: "reading"}) db.users.updateOne({name: "John", hobbies: "reading"}, {$set: {"hobbies.$": "writing"}})

You can also use various array operators like $push, $pull, and $addToSet to add, remove, and manipulate elements within an array:

css
Copy code
db.users.updateOne({name: "John"}, {$push: {hobbies: "painting"}}) db.users.updateOne({name: "John"}, {$pull: {hobbies: "traveling"}}) db.users.updateOne({name: "John"}, {$addToSet: {hobbies: "writing"}})

By using nested documents and arrays, you can create more complex and flexible data models in MongoDB that allow you to store and manipulate a wide variety of data types and structures.


    Leave a Comment


  • captcha text