【发布时间】:2015-03-10 13:10:30
【问题描述】:
我在 mongo db 的集合中有以下类型的文档
{ _id:xx,
iddoc:yy, type1:"sometype1", type2:"sometype2", date: { year:2015, month:4, day:29, type:"day" }, count:23 }
我想对所有文档按 iddoc 分组的字段计数进行总和,其中:
type1 in ["type1A","type1B",...] 其中 type2 在 ["type2A","type2B",...] date.year: 2015, date.month: 4, date.type: "day" date.day 介于 4 和 7 之间
然后我想对这些总和进行排序。
我现在知道怎么做(见this question)
db.test.aggregate([
// Filter the docs based on your criteria
{$match: {
type1: {$in: ['type1A', 'type1B']},
type2: {$in: ['type2A', 'type2B']},
'date.year': 2015,
'date.month': 4,
'date.type': 'day',
'date.day': {$gte: 4, $lte: 7}
}},
// Group by iddoc and count them
{$group: {
_id: '$iddoc',
sum: {$sum: 1}
}},
// Sort by sum, descending
{$sort: {sum: -1}}
])
但希望匹配操作中的某些字段出现在最终文档中。这可能吗?怎么样?
【问题讨论】:
-
按照您目前的方式包含查询可能是个好主意。我知道它基本上显示在您上一个问题的答案中,但是在这个问题的答案中提供参考会很好。
-
好点我在上面加了。
标签: mongodb aggregation-framework