How do I combine two $and statements in an $or statement in mongodb?

后端 未结 3 406
甜味超标
甜味超标 2021-01-23 00:45

I\'m searching mongodb for all messages from a person A to person B as well as all statements from person B to person A. That way I can make a conversation

from: person

3条回答
  •  无人共我
    2021-01-23 01:07

    The answer should be something like this:

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

提交回复
热议问题