【发布时间】:2017-06-06 01:13:48
【问题描述】:
这是我开始的简化集合:
[{
"_id" : ObjectId("577a598ecab5bb4a002c19da"),
"user" : ObjectId("5775549f9fcaae26c9149026"),
"expense" : 12.87,
"created" : ISODate("2016-07-04T12:43:07.181Z")
},
{
"_id" : ObjectId("577a598ecab5bb4a002c19db"),
"user" : ObjectId("5775549f9fcaae26c9149026"),
"expense" : 12.87,
"created" : ISODate("2016-07-06T12:10:07.181Z")
},
{
"_id" : ObjectId("977a598ecai6bb4a002c19du"),
"user" : ObjectId("6775539f9fciae26c9149027"),
"expense" : 12.87,
"created" : ISODate("2016-07-07T10:43:07.181Z")
},
....
]
我想group 并计算created 参数的特定日期的所有users。
我正在尝试,但它不起作用:
db.getCollection('expenses').group({
keyf: function(doc) {
return {
"day_created": doc.created.getDate(),
"user" : doc.user // or "user" : 1
}
},
cond: {},
reduce: function (value, result) {
result.total++;
},
initial: {
total: 0
}
});
相反,各个组完美地工作(日期):
db.getCollection('expenses').group({
keyf: function(doc) {
return {
"day_created": doc.created.getDate()
}
},
cond: {},
reduce: function (value, result) {
result.total++;
},
initial: {
total: 0
}
});
回应:
[
{
"day_created" : 17,
"total" : 5385
},
{
"day_created" : 18,
"total" : 6338
},
....
]
相反,各个组完美地工作(对于用户):
db.getCollection('tickets').group({
key : {user : 1},
cond: {},
reduce: function (value, result) {
result.total++;
},
initial: {
total: 0
}
});
回应:
[
{
"user" : ObjectId("5776f0143543e84a003d53bf"),
"total" : 155
},
{
"user" : ObjectId("577554a89fcaae26c914a8bd"),
"total" : 494
},
...
]
我正在使用 MongoDB shell 版本:3.2.1。如何使用计算字段进行组聚合而其他人不这样做?
【问题讨论】:
-
上述示例文档的预期输出是什么?
-
我的预期输出:[ { "user" : ObjectId("5776f0143543e84a003d53bf"), "day_created" : 17, "total" : 155 }, { "user" : ObjectId("577554a89fcaae26c914a8bd"), "day_created" : 17, "total" : 494 }, ... ]
-
这是所需聚合操作的预期结果“对创建参数的特定日期的所有用户进行分组和计数。”?
-
yes "对创建参数的特定日期的所有用户进行分组和统计。"
标签: mongodb mongodb-query aggregation-framework