【问题标题】:How do I combine two $and statements in an $or statement in mongodb?如何在 mongodb 的 $or 语句中组合两个 $and 语句?
【发布时间】:2015-01-16 05:18:43
【问题描述】:

我正在 mongodb 中搜索从 A 到 B 的所有消息以及从 B 到 A 的所有语句。这样我可以进行对话

从:A 人 AND 到:B 人

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

【问题讨论】:

  • 类似于$and,只需使用整个$and查询作为$or的一个参数
  • 感谢处理器!我是否将整个 $and 括在大括号中?

标签: mongodb


【解决方案1】:

答案应该是这样的:

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

【讨论】:

    【解决方案2】:

    我不熟悉您正在调用的 collection 函数,也不知道您所指的 req 对象是什么,所以请谨慎回答。

    在我看来,您让这件事变得比实际需要的复杂得多。您的 $and 语句很简单,不需要 $and 关键字:

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

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

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

    【讨论】:

    • 我已经省略了查询(排序,...)周围的麻烦,专注于我理解您的实际问题。复制/粘贴这个来代替你以前的代码显然不能开箱即用。
    【解决方案3】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      • 2018-08-10
      • 1970-01-01
      • 2011-02-04
      • 2012-08-01
      • 1970-01-01
      • 2017-03-28
      相关资源
      最近更新 更多