我很难相信这个问题还没有被问过和回答过,但我找不到任何线索。
我有一个MongoDB聚合查询,需要根据另一个字段的存在与否分组,该字段为布尔值。
例如,让我们从这个集合开始:
> db.test.find()
{ "_id" : ObjectId("53fbede62827b89e4f86c12e"),
"field" : ObjectId("53fbede62827b89e4f86c12d"), "name" : "Erik" }
{ "_id" : ObjectId("53fbee002827b89e4f86c12f"), "name" : "Erik" }
{ "_id" : ObjectId("53fbee092827b89e4f86c131"),
"field" : ObjectId("53fbee092827b89e4f86c130"), "name" : "John" }
{ "_id" : ObjectId("53fbee122827b89e4f86c132"), "name" : "Ben" }
有2个文档包含"field"字段,而另外2个则没有。 需要注意的是,每个"field"字段的值可能不同;我们只是想根据其存在与否分组(或者对我来说,非空也可以,因为我没有存储任何空值)。
我尝试使用 $project,但是在那里没有 $exists,而 $cond 和 $ifNull 也没有帮助我。即使不存在该字段,它似乎始终存在:
> db.test.aggregate(
{$project:{fieldExists:{$cond:[{$eq:["$field", null]}, false, true]}}},
{$group:{_id:"$fieldExists", count:{$sum:1}}}
)
{ "_id" : true, "count" : 4 }
我希望以下这个更简单的聚合查询能够运行,但是由于某种原因,$exists不能像这样被支持:
> db.test.aggregate({$group:{_id:{$exists:"$field"}, count:{$sum:1}}})
assert: command failed: {
"errmsg" : "exception: invalid operator '$exists'",
"code" : 15999,
"ok" : 0
} : aggregate failed
Error: command failed: {
"errmsg" : "exception: invalid operator '$exists'",
"code" : 15999,
"ok" : 0
} : aggregate failed
at Error (<anonymous>)
at doassert (src/mongo/shell/assert.js:11:14)
at Function.assert.commandWorked (src/mongo/shell/assert.js:244:5)
at DBCollection.aggregate (src/mongo/shell/collection.js:1149:12)
at (shell):1:9
2014-08-25T19:19:42.344-0700 Error: command failed: {
"errmsg" : "exception: invalid operator '$exists'",
"code" : 15999,
"ok" : 0
} : aggregate failed at src/mongo/shell/assert.js:13
有人知道如何从这样的集合中获取所需的结果吗?
期望结果:
{ "_id" : true, "count" : 2 }
{ "_id" : false, "count" : 2 }
{ $lte: ["$field", null] }
。 - Ricky Boyce$match: { var_name: { $exists : true } }
完全可以正常工作。 我还没有测试过对聚合进行分组的情况。 - nonNumericalFloat