MongoDB 逻辑与操作

看下面两个例子

rs1:PRIMARY> db.display.find({$and: [{$where: '(1386813645 - this.last_active_time > 300)'}, {status: "online"}]}).count()
0
rs1:PRIMARY> db.display.find({$where: '(1386813645 - this.last_active_time > 300)', status: "online"}).count()
0


第一个用了$and operator,意思是数组中两个查询条件是逻辑与的关系,只有两个都为真,才算查询条件匹配。

第二个和第一个等价,是一个隐式的逻辑与操作。一直以来,只有第二中形式,可能是为了更完整吧,2.0之后,MongoDB引入了第一种形式。

参考文档:http://docs.mongodb.org/manual/reference/operator/query/and/

在文档中,还提到了另一种使用方法,就是对一个字段执行逻辑与操作的时候,可以简写为如下形式:

db.inventory.update( { price: { $ne: 1.99, $exists: true } } , { $set: { qty: 15 } } )

只有当price 不等于1.99,并且存在时,才更新qty为15.

所以,我的结论是一般用隐式就好,写起来简单方便。

原文地址:https://www.cnblogs.com/fuhaots2009/p/3471558.html