Ask Your Question
3

How can we deconstruct several arrays in MongoDB?

asked 2023-06-23 00:07:37 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-06-23 00:21:01 +0000

devzero gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-06-23 00:07:37 +0000

Seen: 12 times

Last updated: Jun 23 '23