如何在mongodb的$ or语句中合并两个$ and语句? [英] How do I combine two $and statements in an $or statement in mongodb?

查看:875
本文介绍了如何在mongodb的$ or语句中合并两个$ and语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在mongodb中搜索从一个人A到另一个人B的所有消息,以及从一个人B到另一个人A的所有语句.这样我就可以进行对话

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

从:人员A AND 至:人员B

from: person A AND to: personB

OR

从:人B AND 到人A

// Create a conversation
db.collection('messages', function (err, collection) {
    collection.find(
        { // how do I turn this $and into a two nested $and statements inside $or?
            $and: [{
                receiver: new BSON.ObjectID(req.user._id)
            }, {
                sender: new BSON.ObjectID(req.body.sender)
            }]
        }
    ).sort({
        date: -1
    }).toArray(function (err, docs) {
        console.log(docs);
    })
});

推荐答案

我不熟悉您正在调用的collection函数,并且不知道您所指的req对象是什么,所以我的回答是一粒盐.

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.

在我看来,您正在使这一过程变得比实际需要复杂得多.您的$and语句很简单,不需要$and关键字:

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

现在,$and$or的工作方式完全相同:它们采用一组对象.因此,让我们写一下我假设您希望查询的内容:

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

这篇关于如何在mongodb的$ or语句中合并两个$ and语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆