or between two and operator in mongodb

Viewed 141

My collection is collection

{
    "_id" : ObjectId(""),
    "from" : 1,
    "to" : 2,
    "message" : "Hello",
}
{
    "_id" : ObjectId(""),
    "from" : 2,
    "to" : 1,
    "message" : "Hi",
}

I want to execute SQL query like

select * from collection where (from=1 and to=2) or (from=2 and to=1)

In mongodb I am using

db.getCollection('collection').find({
    $or:[{
      $and:[  
        {"from": 1},
        {"to":   2},
        ],
        $and:[
    {"from": 2},
    {"to": 1},
               ]
    }]
        })

But It returns 0 records fetch.

So How to use (and) or (and) in mongodb

1 Answers

Your syntax was slightly off:

db.getCollection('collection').find({
    $or:[{ $and:[{"from": 1}, {"to": 2}] },
         { $and:[{"from": 1}, {"to": 1}] }]
})

Each of the items inside the $or array needs to be in a closure {...}.

Related