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

Wie kombiniere ich zwei $and-Anweisungen in einer $or-Anweisung in Mongodb?

Die Antwort sollte in etwa so lauten:

db.collection('messages', function (err, collection) {
    collection.find(
        { 
        $or : [         
            {$and: [{
                receiver: new BSON.ObjectID(req.user._id)
            }, {
                sender: new BSON.ObjectID(req.body.sender)
            }]},
            {$and: [{
                receiver: new BSON.ObjectID(req.body.sender)
            }, {
                sender: new BSON.ObjectID(req.user._id)
            }]},
        ]
        }
    ).sort({
        date: -1
    }).toArray(function (err, docs) {
        console.log(docs);
    })
});