1

在 mongoDB 中,我们如何获取数组中特定键的计数

{
 "_id" : ObjectId("52d9212608a224e99676d378"),
 "business" : [
  {
   "name" : "abc",
   "rating" : 4.5
  },
  {
   "name" : "pqr"
  },
  {
   "name" : "xyz",
   "rating" : 3.6
  }
 ]
}

在上面的例子中,business 是一个数组(带有“name”和/或“rating”键)

如何获得仅存在“评级”键的业务阵列计数?

预期输出为:2

4

1 回答 1

7

看起来你必须使用Aggregation Framework。特别是您需要$unwind您的数组,然后仅匹配包含rating字段的元素,然后将$group文档恢复为原始格式。

尝试这样的事情:

db.test.aggregate([
    { $match: { /* your query criteria document */ } },
    { $unwind: "$business" },
    { $match: {
        "business.rating": { $exists: 1 }
      }
    },
    { $group: {
        _id: "$_id",
        business: { $push: "$business" },
        business_count: { $sum: 1 }
      }
    }
])

结果将如下所示:

{
  _id: ObjectId("52d9212608a224e99676d378"),
  business: [
    { name: "abc", rating: 4.5 },
    { name: "xyz", rating: 3.6 }
  ],
  business_count: 2
}

UPD看起来 OP 不想通过包装文档_id字段来对结果进行分组。不幸的是,$group表达式必须指定_id值,否则它会因异常而失败。但是,这个值实际上可以是常数(例如plainnull'foobar'),因此只有一个结果组具有collection-wise 聚合。

于 2014-01-17T13:12:51.647 回答