【问题标题】:MongoDB $match not working for part of sub documentMongoDB $match 不适用于部分子文档
【发布时间】:2015-04-06 20:38:09
【问题描述】:

在我的 MongoDB 中,我正在尝试使用 aggregate() 函数和 group by”一组记录>$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 查找。

由于 user 不是数组,我不能对其使用 $unwind

我如何做到这一点?

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-03
      • 2018-07-06
      • 2014-10-14
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      • 2019-03-25
      • 1970-01-01
      相关资源
      最近更新 更多