Filtering an embedded array in MongoDB

后端 未结 2 676
南方客
南方客 2021-01-27 07:29

I have a Mongodb document that contains an an array that is deeply imbedded inside the document. In one of my action, I would like to return the entire document but filter out t

2条回答
  •  礼貌的吻别
    2021-01-27 08:12

    You can use $addToSet on the group after unwinding and matching by listed equals true.

    Sample shell query:

    db.collection.aggregate([
    {
        $unwind: "$vehicles"
    },
    {
        $match: {
            "vehicles.listed": {
                $eq: true
            }
        }
    },
    {
        $group: {
            _id: "$id",
            vehicles: {
                "$addToSet": {
                    name: "$vehicles.name",
                    listed: "$vehicles.listed"
                }
            }
        }
    },
    {
        $project: {
            _id: 0,
            id: "$_id",
            vehicles: 1
        }
    }
    ]).pretty();
    

提交回复
热议问题