在我的MongoDB中,我试图使用aggregate()函数对一组记录进行“分组”,并且我使用的$ match查询不会选择管道中的记录。
我的数据集有一些子文档(在上面应用了$ match),它看起来像这样:
{
"_id" : ObjectId("550994e21cba9597624195aa"),
"taskName" : "task name",
"taskDetail" : "task detail.",
"scheduledStartDate" : ISODate("2015-04-06T09:00:00.000Z"),
"scheduledEndDate" : ISODate("2015-04-06T11:00:00.000Z"),
"user" : {
"id" : "abcd1123",
"name" : "username"
},
"status" : "Assigned"
}
{
"_id" : ObjectId("550994e21cba9597624195aa"),
"taskName" : "task name",
"taskDetail" : "task detail.",
"scheduledStartDate" : ISODate("2015-04-06T09:00:00.000Z"),
"scheduledEndDate" : ISODate("2015-04-06T11:00:00.000Z"),
"user" : {
"id" : "abcd1123",
"name" : "username"
},
"status" : "Assigned"
}
{
"_id" : ObjectId("550994e21cba9597624195aa"),
"taskName" : "task name",
"taskDetail" : "task detail.",
"scheduledStartDate" : ISODate("2015-04-06T09:00:00.000Z"),
"scheduledEndDate" : ISODate("2015-04-06T11:00:00.000Z"),
"user" : {
"id" : "abcd1124",
"name" : "username"
},
"status" : "Assigned"
}
我想找出按状态类型分组的特定用户的状态计数。对于用户“ abcd1123”,我使用的查询是:
db.tasks.aggregate( [
{
$match : {
user : { id : "abcd1123" }
}
},
{
$group: {
_id: "$status",
count: { $sum: 1 }
}
}
] )
上面的查询不返回任何结果,因为$ match不会将任何结果放入管道中。如果我这样修改查询:
db.tasks.aggregate( [
{
$match : {
user : { id : "abcd1123", name : "username" }
}
},
{
$group: {
_id: "$status",
count: { $sum: 1 }
}
}
] )
有用。但是我没有用户名作为输入,我只需要根据用户ID查找即可。
由于用户不是数组,因此无法在其上使用$ unwind。
我如何做到这一点?
您太接近了,只能按以下方式更改汇总查询
db.collectionName.aggregate({
"$match": {
"user.id": "abcd1123"
}
},
{
"$group": {
"_id": "$status",
"count": {
"$sum": 1
}
}
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句