Search⌘ K
AI Features

Reading Arrays from Documents

Explore how to read and query array fields in MongoDB documents using essential query operators. Understand how to filter, project, and retrieve data from arrays, including nested arrays, to manage document data efficiently and analyze it accurately.

Understanding arrays in MongoDB

In MongoDB, an array is a list of values within a field of a document. These values can be of any data type:

  • Strings: ["reading", "cycling", "music"]

  • Numbers: [1, 2, 3, 4]

  • Objects: [ { "name": "Alice" }, { "name": "Bob" } ]

  • Nested arrays: [ [1, 2], [3, 4] ]

Visually, we can see them as below.

Arrays in MongoDB
Arrays in MongoDB

A MongoDB document can have multiple values for a single field. In our case, the users collection contains a field, orderHistory, which is an array of objects. See the snippet below.

Javascript (babel-node)
{
"id": "0001",
"name": "Allison Hill",
"email": "allison.hill546@icloud.com",
"password": "c9bc39914ae4497ea94dc59182b7dfe204445f817e4a880f259b1c29e2046a4f",
"phoneNo": "985-559-7734",
"address": [
{
"street": "26542 Susan Junction Apt. 161",
"city": "Washington",
"postalCode": "20001",
"country": "United States"
}
],
"orderHistory": [
{
"id": "3000"
},
{
"id": "3001"
},
{
"id": "3002"
},
{
"id": "3003"
}
]
}

In the document above, the orderHistory field has an array, which contains four objects: "id": "3000", "id": "3001", "id": "3002", and "id": ...

Javascript (babel-node)
{
"_id": {
"id": "5000"
},
"name": "Electronics",
"parentCategory": null,
"subCategories": [
{
"name": "Computers",
"subCategories": [
{
"name": "Laptops"
},
{
"name": "Accessories"
}
]
},
{
"name": "Mobile Phones",
"subCategories": [
{
"name": "Smartphones"
},
{
"name": "Accessories"
}
]
}
]
}
...