What is the usage of the “unwind” function in MongoDB?

In MongoDB, $unwind is an aggregation operator used to deconstruct an array field. It splits the array field into multiple documents, each containing only one element from the array. This operation is typically used for grouping and filtering fields that contain arrays.

For instance, if there is a field “students” containing an array, the $unwind operator can be used to unfold this field into multiple documents, with each document containing information about one student. This enables easier manipulation and filtering of each student.

For example, consider the following document structure:

{
  "_id": 1,
  "class": "A",
  "students": ["Alice", "Bob", "Charlie"]
}
{
  "_id": 2,
  "class": "B",
  "students": ["David", "Eve"]
}

By using the $unwind operator:

db.collection.aggregate([
  { $unwind: "$students" }
])

After performing the above operation, the following results will be obtained:

{
  "_id": 1,
  "class": "A",
  "students": "Alice"
}
{
  "_id": 1,
  "class": "A",
  "students": "Bob"
}
{
  "_id": 1,
  "class": "A",
  "students": "Charlie"
}
{
  "_id": 2,
  "class": "B",
  "students": "David"
}
{
  "_id": 2,
  "class": "B",
  "students": "Eve"
}

We can see that the $unwind operator separates the “students” field in the original document into multiple documents, each containing information for only one student.

Leave a Reply 0

Your email address will not be published. Required fields are marked *