86

How would I have multiple $or operations? So far I've tried the following but it silently ignores the 2nd $or.

{
  $or: [{a: 2}, {a: 3}], 
  $or: [{b: 5}, {b: 4}]
}

I assume this is because I'm using two identical keys. Is there any way around this?

Mike Neumegen
  • 2,436
  • 1
  • 24
  • 39

3 Answers3

156

Mongo 2.0 added an $and operator, so you can do a query like this:

db.things.find({$and: [{$or : [{'a':1},{'b':2}]},{$or : [{'a':2},{'b':3}]}] })

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24and

Nader
  • 5,493
  • 4
  • 33
  • 31
-3

For multiple like in sql we use $in and for not we use $nin vc is our collection name here.We are finding those string contains cpu or memo.

db.collection('vc').find({   "name" :   { $in: [ /cpu/, /memo/ ]   }     }
Gajender Singh
  • 1,285
  • 14
  • 13
-6

$and will not do the job, since the 2nd $or will not validate if the first one fails.

From the Mongo man page:

The $and operator uses short-circuit evaluation. If the first expression (e.g. ) evaluates to false, MongoDB will not evaluate the remaining expressions.

Nested $or however should do the trick:

db.things.find({$or: [{$or : [{'a':1},{'b':2}]},{$or : [{'a':2},{'b':3}]}] })