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.
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.
In the document above, the orderHistory field has an array, which contains four objects: "id": "3000", "id": "3001", "id": "3002", and "id": ...