看起来你必须使用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 聚合。