MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

MongoDB filtert mehrere Unterdokumente

Verwenden Sie die folgende Aggregationspipeline, um das gewünschte Ergebnis zu erhalten:

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');
        });

Oder Sie können die Aggregationspipeline verwenden Builder wie folgt:

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);