...

/

Reading Arrays from Documents

Reading Arrays from Documents

Explore working with arrays in MongoDB, including querying for specific values, using operators like $in, $nin, $all, and $size, to filter and manipulate array data in documents.

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.

Press + to interact
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.

Press + to interact
{
"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": "3003". ...