mxs
mxs

Reputation: 645

Mongo $OR nested within $AND

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}},
        ]
      },
    ]
  }
)

Upvotes: 4

Views: 2696

Answers (1)

chridam
chridam

Reputation: 103435

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.

Upvotes: 3

Related Questions