How to access nested arrays in mongodb?

Member

by brandy , in category: MySQL , a month ago

How to access nested arrays in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by larissa , a month ago

@brandy 

To access nested arrays in MongoDB, you can use dot notation to navigate through the levels of the nested arrays.


For example, let's say you have a document with the following structure:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
{
   "_id": 1,
   "name": "John",
   "contacts": [
      {
         "type": "email",
         "value": "[email protected]"
      },
      {
         "type": "phone",
         "value": "123-456-7890"
      }
   ]
}


To access the "email" value within the "contacts" array, you would use the following query:

1
db.collection.find({_id: 1}, { "contacts.value": 1 })


This will return the document with only the "value" field of the "contacts" array that has "type" equal to "email".


You can also use the aggregation framework to work with nested arrays in more complex ways. Here's an example using the aggregation framework to unwind the "contacts" array and project only the "value" field with "type" equal to "email":

1
2
3
4
5
6
db.collection.aggregate([
   { $match: { _id: 1 } },
   { $unwind: "$contacts" },
   { $match: { "contacts.type": "email" } },
   { $project: { "contacts.value": 1, _id: 0 } }
])


This will return the same result as the previous query but using the aggregation framework.


By using dot notation and the aggregation framework, you can effectively access and manipulate nested arrays in MongoDB.