结合$或$和MongoDB

时间:2016-08-19 22:34:54

标签: node.js mongodb mongoose database

你如何在Mongo中执行以下sql?

SELECT * FROM messages WHERE (sender='me' AND recipient='them') OR (sender='them' AND recipient='me')

psuedocode查询示例:

(sender == me && recipient == them) || (sender == them && recipient <= me)

我试图获取我('我')发送给'他们'的所有消息或反过来(我从'他们'收到的所有消息)。

我无法获得$或$和一起工作......

我正在使用Mongo 3.2.8和Mongoose(使用Node.js)

2 个答案:

答案 0 :(得分:0)

我试过..在下面创建了一个示例数据集,看起来很有效

试试这个

set.seed(0); x <- sample(0:3, 20, TRUE)
# [1] 3 1 1 2 3 0 3 3 2 2 0 0 0 2 1 3 1 2 3 1

k <- rle(as.logical(x))$lengths    ## chunk size
# [1] 5 1 4 3 7

ave(x, rep.int(1:length(k), k), FUN = cumsum)    ## cumulative sum each chunk
# [1]  3  4  5  7 10  0  3  6  8 10  0  0  0  2  3  6  7  9 12 13

检查集合

> db.messages.insert({"sender":"me","recipient":"them"})
WriteResult({ "nInserted" : 1 })
> db.messages.insert({"sender":"them","recipient":"me"})
WriteResult({ "nInserted" : 1 })
> db.messages.insert({"sender":"a","recipient":"b"})
WriteResult({ "nInserted" : 1 })
> db.messages.insert({"sender":"me","recipient":"b"})
WriteResult({ "nInserted" : 1 })
> db.messages.insert({"sender":"them","recipient":"b"})
WriteResult({ "nInserted" : 1 })

查询

> db.messages.find();
{ "_id" : ObjectId("57b78b2c8d2d515b0309868e"), "sender" : "me", "recipient" : "them" }
{ "_id" : ObjectId("57b78b3a8d2d515b0309868f"), "sender" : "them", "recipient" : "me" }
{ "_id" : ObjectId("57b78b418d2d515b03098690"), "sender" : "a", "recipient" : "b" }
{ "_id" : ObjectId("57b78b468d2d515b03098691"), "sender" : "me", "recipient" : "b" }
{ "_id" : ObjectId("57b78b4c8d2d515b03098692"), "sender" : "them", "recipient" : "b" }

输出

> db.messages.find({"$or":[{"sender":"me","recipient":"them"},{"sender":"them","recipient":"me"}]});

&GT;

答案 1 :(得分:0)

{$or: [ {sender: "me", recipient:"them"}, {sender: "them", recipient:"me"} ] }