发布于 2015-09-14 15:01:04 | 130 次阅读 | 评论: 0 | 来源: 网络整理
2.0 新版功能.
Syntax: { $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }
$and performs a logical AND operation on an array of two or more expressions (e.g. <expression1>, <expression2>, etc.) and selects the documents that satisfy all the expressions in the array. The $and operator uses short-circuit evaluation. If the first expression (e.g. <expression1>) evaluates to false, MongoDB will not evaluate the remaining expressions.
Consider the following example:
db.inventory.find({ $and: [ { price: 1.99 }, { qty: { $lt: 20 } }, { sale: true } ] } )
This query will select all documents in the inventory collection where:
MongoDB provides an implicit AND operation when specifying a comma separated list of expressions. For example, you may write the above query as:
db.inventory.find( { price: 1.99, qty: { $lt: 20 } , sale: true } )
If, however, a query requires an AND operation on the same field such as { price: { $ne: 1.99 } } AND { price: { $exists: true } }, then either use the $and operator for the two separate expressions or combine the operator expressions for the field { price: { $ne: 1.99, $exists: true } }.
Consider the following examples:
db.inventory.update( { $and: [ { price: { $ne: 1.99 } }, { price: { $exists: true } } ] }, { $set: { qty: 15 } } )
db.inventory.update( { price: { $ne: 1.99, $exists: true } } , { $set: { qty: 15 } } )
Both update() operations will set the value of the qty field in documents where: