发布于 2015-09-14 15:01:04 | 119 次阅读 | 评论: 0 | 来源: 网络整理

$and

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:

  • price field value equals 1.99 and
  • qty field value is less than 20 and
  • sale field value is equal to true.

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:

  • the price field value does not equal 1.99 and
  • the price field exists.

也可以参考

find(), update(), $ne, $exists, $set.

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务