To deconstruct an array in MongoDB, we can use the $unwind
operator.
Let's suppose we have a collection named "students" with the following documents:
{
"_id": 1,
"name": "John",
"grades": [81, 73, 92]
}
{
"_id": 2,
"name": "Mary",
"grades": [87, 78, 95]
}
If we want to deconstruct the grades
array of each document, we can use the following query:
db.students.aggregate([
{ $unwind: "$grades" }
])
The result will be:
{ "_id": 1, "name": "John", "grades": 81 }
{ "_id": 1, "name": "John", "grades": 73 }
{ "_id": 1, "name": "John", "grades": 92 }
{ "_id": 2, "name": "Mary", "grades": 87 }
{ "_id": 2, "name": "Mary", "grades": 78 }
{ "_id": 2, "name": "Mary", "grades": 95 }
The $unwind
operator creates a new document for each element in the array, with the same values for all fields except for the field being unwound (grades
in this case). This allows us to perform aggregation operations on the individual elements of the array.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-06-23 00:07:37 +0000
Seen: 12 times
Last updated: Jun 23 '23
How do you log Python data into a database?
Is it possible to query a unique index directly instead of querying a collection in MongoDB?
What is the process of integrating API data into MongoDB using Spark/Python?
Please help me with connecting my MongoDB to my JS file as I am struggling to do so.
How can additional fields that have been transformed be queried in MongoDB?