MongoDB - Multiple $or operations

KeyMongodb

Key Problem Overview


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?

Key Solutions


Solution 1 - Key

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

Solution 2 - Key

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/ ]   }     }

Solution 3 - Key

You can not nest multiple $or statements.

This is documented here:

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

Apart from that: your query does make much sense.

If you are trying to query for a being either 2 or 3 and b being either 5 or 4:

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

Please don't try to invent new syntax.

Solution 4 - Key

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMike NeumegenView Question on Stackoverflow
Solution 1 - KeyNaderView Answer on Stackoverflow
Solution 2 - KeyGajender SinghView Answer on Stackoverflow
Solution 3 - KeyAndreas JungView Answer on Stackoverflow
Solution 4 - Keyuser1231157View Answer on Stackoverflow