如何在mongodb中的$或语句中组合两个$和语句?

时间:2015-01-15 20:57:01

标签: mongodb

我正在搜索mongodb,查看从A到B的所有消息以及从B到A的所有陈述。这样我就可以进行对话

从:人A AND 到:personB

从:B人 AND 到personA

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

3 个答案:

答案 0 :(得分: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);
    })
});

答案 1 :(得分:2)

我不熟悉您正在调用的collection函数,并且不知道您所指的req对象是什么,所以请尽量回答我的答案。< / p>

在我看来,你做的比实际需要的要复杂得多。您的$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
    }]
})

答案 2 :(得分: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);
    }) });