MongoDB filter multi sub-documents

早过忘川 提交于 2019-12-06 04:29:10

Use the following aggregation pipeline to get the desired result:

var pipeline = [
    {
        "$match": {
            "name": "Andre",
            "fruits.active": true,
            "cars.active": true
        }
    },
    { "$unwind": "$fruits" },
    { "$unwind": "$cars" },
    {
        "$match": {            
            "fruits.active": true,
            "cars.active": true
        }
    },
    { 
        "$group": {
            "_id": {
                "_id": "$_id",
                "name": "$name"
            },
            "cars": { "$addToSet" : "$cars" },
            "fruits": { "$addToSet" : "$fruits" }
        }
    },
    {
        "$project": {
            "_id": 0,
            "name": "$_id.name",
            "cars": 1,
            "fruits": 1
        }
    }    
]

m_object.aggregate(pipeline)
        .exec(function (err, result) {
            if (err) {
                console.log(err);
                return;
            }
            console.log('result');
        });

Or you can use the aggregation pipeline builder as follows:

m_object.aggregate()
        .match({
            "name": "Andre",
            "fruits.active": true,
            "cars.active": true
         })
        .unwind("fruits")
        .unwind("cars")
        .match({
            "fruits.active": true,
            "cars.active": true
         })
        .group({
            "_id": {
                "_id": "$_id",
                "name": "$name"
            },
            "cars": { "$addToSet" : "$cars" },
            "fruits": { "$addToSet" : "$fruits" }
        })
        .project({
            "_id": 0,
            "name": "$_id.name",
            "cars": 1,
            "fruits": 1
        })
        .exec(callback);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!