Select sub-documents where field's value is in an some array

后端 未结 2 1529
闹比i
闹比i 2021-01-21 00:46

I want to filter according the sub documents, but actually I am repeating the document for each sub document. I want one document and a list of sub documents if that is the case

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-21 01:39

    You just need to add $group & $push. First you $unwind the subdocs to apply the $match followed by $group on id and $push the grouped subdocs.

    db.ftmp.aggregate({
        $unwind: "$subdocs"
    }, {
        $match: {
            "subdocs.desc": {
                $in: ["000", "011"]
            }
        }
    }, {
        $group: {
            _id: "$_id",
            subdocs: {
                $push: "$subdocs"
            },
            filename: {
                $first: "$filename"
            },
            cod: {
                $first: "$cod"
            }
        }
    })
    

提交回复
热议问题