MongoDB $match 不适用于部分子文档

MongoDB $match not working for part of sub document

在我的 MongoDB 中,我正在尝试使用 [=29] 对一组记录进行“分组 ” =]aggregate() 函数和我使用的 $match 查询不会 select 管道中的记录。

我的数据集有子文档(我在其上应用了 $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 }
       }
   }
] )

上面的查询没有 return 任何结果,因为 $match 没有将任何结果放入管道。如果我这样修改查询:

db.tasks.aggregate( [
   {
       $match : {
           user : { id : "abcd1123", name : "username" } 
       }
   },
   {
       $group: {
          _id: "$status",
          count: { $sum: 1 }
       }
   }
] )

有效。但是我没有用户名作为输入,我只需要根据用户 ID 查找。

因为 user 不是一个数组,我不能在上面使用 $unwind

我该如何实现?

你太接近了,只改变你的聚合查询如下

db.collectionName.aggregate({
    "$match": {
    "user.id": "abcd1123"
    }
},
{
    "$group": {
    "_id": "$status",
    "count": {
        "$sum": 1
    }
    }
})