Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo $OR nested within $AND

Tags:

mongodb

meteor

I'm trying to construct a Mongo query that gets all documents meeting multiple $AND conditions as well as one or more $OR conditions. My approach is below.

The $AND condition seems to be working as expected, but when I add the $OR, the results do not change. Any help is appreciated.

Collection.find({
    $and:[
      {lat: { $ne:""}},
      {lon: { $ne:""}},
      {type : "foo"},            
      {keywords:{ $regex : "bar", $options:"i" }},
      { $or:[
        {isOpen : "True"},
        {isOpen : "False"},              
        {price : { $gte: 0}},
        ]
      },
    ]
  }
)
like image 319
mxs Avatar asked Oct 15 '25 04:10

mxs


1 Answers

Just create a query where you only specify a comma delimited list of expressions as it implicitly does the AND operation for you. You can then include the or query in the list as follows:

var query = {
    lat: { $ne: ""},
    lon: { $ne:"" },
    type: "foo",            
    keywords: { $regex : "bar", $options:"i" },
    $or: [
        { isOpen: "True"},
        { isOpen: "False"},              
        { price: { $gte: 0}},
    ]
};

Collection.find(query);

You can refer the docs:

MongoDB provides an implicit AND operation when specifying a comma separated list of expressions. Using an explicit AND with the $and operator is necessary when the same field or operator has to be specified in multiple expressions.

like image 54
chridam Avatar answered Oct 18 '25 00:10

chridam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!