Filtering an embedded array in MongoDB

后端 未结 2 677
南方客
南方客 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();
    
    0 讨论(0)
  • 2021-01-27 08:23

    You could use aggregation framework like this:

    db.test312.aggregate(
        {$unwind:"$vehicles"},
        {$match:{"vehicles.name":"Nissan"}},
        {$group:{_id:"$_id",vehicles:{$push:"$vehicles"}}}
    )
    
    0 讨论(0)
提交回复
热议问题