MongoDB-多个 $或操作

如何使用多个 $或操作? 到目前为止,我已经尝试了以下方法,但它默认忽略了第2个 $或操作。

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

我猜是因为我用了两把一模一样的钥匙,有办法解决吗?

29998 次浏览

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.

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

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

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