📜  Unwind Mongodb (1)

📅  最后修改于: 2023-12-03 14:48:13.852000             🧑  作者: Mango

Unwind Mongodb

In MongoDB database, Unwind is one of the most commonly used data aggregation operators. Unwind operator takes an array and converts it into individual documents. This helps to perform further operations on the data in much organized manner.

Syntax

The basic syntax of the unwind operator is:

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

Here $unwind operator is used to create a new document for each element of the array specified by the field_name.

Parameters

The $unwind operator takes the following parameters:

  • $path: the field name that contains the array to unwind. This parameter is required.
  • $includeArrayIndex: (optional) if you want to include the index of the array element in the unwound documents, specify true. Default is false.
  • $preserveNullAndEmptyArrays: (optional) if you want to include the documents where the array is empty or null, specify true.
Example

Consider the following students collection with documents having nested "subjects" array:

{
   "_id": 1,
   "name": "John Doe",
   "subjects": [
      "Math",
      "Science",
      "History"
   ]
},
{
   "_id": 2,
   "name": "Jane Smith",
   "subjects": [
      "Math",
      "Science"
   ]
},
{
   "_id": 3,
   "name": "Bob Johnson",
   "subjects": []
}

To unwind the "subjects" array and get separate documents for each subject, we can use the following query:

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

This will produce the following output:

{
   "_id": 1,
   "name": "John Doe",
   "subjects": "Math"
},
{
   "_id": 1,
   "name": "John Doe",
   "subjects": "Science"
},
{
   "_id": 1,
   "name": "John Doe",
   "subjects": "History"
},
{
   "_id": 2,
   "name": "Jane Smith",
   "subjects": "Math"
},
{
   "_id": 2,
   "name": "Jane Smith",
   "subjects": "Science"
}
Conclusion

The $unwind operator is a powerful tool for organizing and manipulating data in MongoDB. By converting arrays into individual documents, it allows for greater flexibility and ease of use in performing data aggregation operations.