我有这样的文件
{
"_id": ObjectId("524a498ee4b018b89437f88a"),
"counter": {
"0": {
"date": "2013.9",
"counter": NumberInt(1425)
},
"1": {
"date": "2013.10",
"counter": NumberInt(1425)
}
},
"profile": ObjectId("510576242b5e30877c654aff")
}
我想搜索那些,counter.0.counter不等于counter.1.counter
tryed
db.counter.find({"profile":ObjectId("510576242b5e30877c654aff"),"counter.0.counter":{$ne:"counter.1.counter"} });
但它说它不是一个有效的json查询:/ 一个帮助?
答案 0 :(得分:2)
两件事。
除非使用JavaScript或使用聚合框架,否则无法像这样进行比较。带聚合的表单是更好的选择:
db.collection.aggregate([
{ "$project": {
"counter": 1,
"matched": { "$eq": [
"$counter.0.counter",
"$counter.1.counter"
]}
}},
{ "$match": { "matched": true } }
])
或者使用JavaScript很糟糕:
db.collection.find({
"$where": function() {
return this.counter.0.counter == this.counter.1.counter;
}
})
所以这就是可以做到的方法。
JavaScript $where
运算符存在的主要问题是:
调用JavaScript解释器来评估每个结果文档,而不是本机代码。
根据需要,删除使用索引查找结果的任何机会。通过其他方法,您实际上可以使用具有单独“匹配”条件的索引。但是这个操作员消除了这个机会。