mongodb unwind array nested inside an array of documents

后端 未结 1 1983
南旧
南旧 2021-02-08 12:44

In MongoDB, I need to be able to unwind nested an array in a document inside an array inside the main document.

{
    \"         


        
1条回答
  •  太阳男子
    2021-02-08 13:12

    In unwind stage, field should be an array field. If not array field, it treats it as array of 1 element.

    From the docs:

    Changed in version 3.2: $unwind stage no longer errors on non-array operands. If the operand does not resolve to an array but is not missing, null, or an empty array, $unwind treats the operand as a single element array.


    Answer to your query:

    db.response.aggregate([
        {
            $project:
            {
                "job_details.label_name":1,
                _id:0
            }
        },
        {
            $unwind:"$job_details.label_name"
        },
        {
            $group:
            {
                _id:"$job_details.label_name",
                count:{$sum:1}
            }
        }
    ])
    

    Refer Shell Output

    0 讨论(0)
提交回复
热议问题