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

后端 未结 3 402
甜味超标
甜味超标 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:23

    I'm unfamiliar with the collection function you're calling and do not know what the req object you're referring to is, so take my answer with a grain of a salt.

    It seems to me that you're making this much more complicated than it really needs to be. Your $and statement is trivial enough that it does not need the $and keyword:

    collection.find({
        receiver: req.user._id,
        sender:   req.body.sender
    })
    

    Now, $and and $or work exactly the same way: they take an array of objects. So let's write what I assume you intended your query to be:

    collection.find({
        $or: [{
            receiver: req.user._id,
            sender:   req.body.sender
        }, {
            receiver: req.body.sender,
            sender:   req.user_id
        }]
    })
    

提交回复
热议问题