MongoDB - Multiple $or operations
KeyMongodbKey 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.
Nested $or however should do the trick:
db.things.find({$or: [{$or : [{'a':1},{'b':2}]},{$or : [{'a':2},{'b':3}]}] })