What's the $unwind operator in MongoDB?

后端 未结 6 1086
日久生厌
日久生厌 2020-11-27 12:41

This is my first day with MongoDB so please go easy with me :)

I can\'t understand the $unwind operator, maybe because English is not my native language

6条回答
  •  执笔经年
    2020-11-27 13:05

    As per mongodb official documentation :

    $unwind Deconstructs an array field from the input documents to output a document for each element. Each output document is the input document with the value of the array field replaced by the element.

    Explanation through basic example :

    A collection inventory has the following documents:

    { "_id" : 1, "item" : "ABC", "sizes": [ "S", "M", "L"] }
    { "_id" : 2, "item" : "EFG", "sizes" : [ ] }
    { "_id" : 3, "item" : "IJK", "sizes": "M" }
    { "_id" : 4, "item" : "LMN" }
    { "_id" : 5, "item" : "XYZ", "sizes" : null }
    

    The following $unwind operations are equivalent and return a document for each element in the sizes field. If the sizes field does not resolve to an array but is not missing, null, or an empty array, $unwind treats the non-array operand as a single element array.

    db.inventory.aggregate( [ { $unwind: "$sizes" } ] )
    

    or

    db.inventory.aggregate( [ { $unwind: { path: "$sizes" } } ] 
    

    Above query output :

    { "_id" : 1, "item" : "ABC", "sizes" : "S" }
    { "_id" : 1, "item" : "ABC", "sizes" : "M" }
    { "_id" : 1, "item" : "ABC", "sizes" : "L" }
    { "_id" : 3, "item" : "IJK", "sizes" : "M" }
    

    Why is it needed?

    $unwind is very useful while performing aggregation. it breaks complex/nested document into simple document before performaing various operation like sorting, searcing etc.

    To know more about $unwind :

    https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/

    To know more about aggregation :

    https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/

提交回复
热议问题