在聚合过程中,我得到了以下数据:
{
"_id" : "billing/DefaultController/actionIndex",
"min_time" : 0.033,
"max_time" : 5.25,
"exec_time" : 555.490999999997,
"qt" : 9059,
"count" : 2,
"date" : [
ISODate("2014-02-10T00:00:00.000Z"),
ISODate("2014-02-11T00:00:00.000Z")
]
},
如何更改我的查询:
db.page_speed_reduced.aggregate([
{$group: {
_id: "$value.route",
min_time: {$min: "$value.min_time"},
max_time: {$max: "$value.max_time"},
exec_time: {$sum: "$value.exec_time"},
qt: {$sum: "$value.qt"},
count: {$sum: NumberInt(1)},
date: {$push: "$_id.date"},
}}
]);
获取“$date”作为连接字符串:
2014-02-10, 2014-02-11
更新:
我尝试了这个变体,但 mongodb 生成了错误:
db.page_speed_reduced.aggregate([
{$group: {
_id: "$value.route",
min_time: {$min: "$value.min_time"},
max_time: {$max: "$value.max_time"},
exec_time: {$sum: "$value.exec_time"},
qt: {$sum: "$value.qt"},
count: {$sum: NumberInt(1)},
date: {$push: "test sting"},
}},
{$project: {
'date': {$concat: ['$date']}
//'date': {$concat: '$date'} //some error
}}
]);
uncaught exception: aggregate failed: {
"errmsg" : "exception: $concat only supports strings, not Array",
"code" : 16702,
"ok" : 0
}
'date': {$concat: '$date'}
最佳答案
根据到目前为止的评论,目前还不清楚您要分组的内容或您想要的最终结果是什么,只是说您希望将日期连接成“只是一天”之类的内容,而没有在一起的小时或分钟。想必您希望这些不同的日子有某种目的。
有各种Date Operators在管道中,您可以在日期上使用,并且是 $concat运营商也是如此。不幸的是,所有日期运算符都会生成一个整数作为其结果,并且对于您想要的日期字符串的排序,$concat仅适用于字符串。另一个问题是您无法在聚合中将整数转换为字符串类型。
但是您可以使用子文档,这里我们只使用日期:
db.record.aggregate([
// Unwind the array to work with it
{$unwind: "$date"},
// project into our new 'day' document
{$project:{
day: {
year: {$year: "$date"},
month: {$month: "$date"},
day: {$dayOfMonth: "$date"}
}
} },
// optionalally sort if date order is important [ oldest -> newest ]
{$sort: { "day.year": -1, "day.month": -1, "day.day": -1}},
// Wind back unique values into the array
{$group: {_id:"$_id", days: {$addToSet: "$day"} }}
])
所以,它不是一个字符串,但它可以很容易地被后处理成一个字符串,但最重要的是它是分组和可排序的。
如果您希望以这种方式将唯一的日期
作为末尾的数组,或者您是否希望按这些日期对总计进行分组,则原则保持不变。因此,请主要记住使用日期运算符的 $unwind 和 $project 部分。
--编辑--
感谢 this post 中所示的社区$substr 有一种未记录的行为,其中整数可以转换为字符串。
db.record.aggregate([
// Unwind the array to work with it
{$unwind: "$date"},
// project into our new 'day' document
{$project:{
day: {
year: {$year: "$date"},
month: {$month: "$date"},
day: {$dayOfMonth: "$date"}
}
} },
// optionalally sort if date order is important [ oldest -> newest ]
{$sort: { "day.year": -1, "day.month": -1, "day.day": -1}},
// now we are going to project to a string ** magic @heinob **
{$project: {
day: {$concat: [
{$substr: [ "$day.year", 0, 4 ]},
"-",
{$substr: [ "$day.month", 0, 2 ]},
"-",
{$substr: [ "$day.day", 0, 2 ]}
]}
}},
// Wind back unique values into the array
{$group: {_id:"$_id", days: {$addToSet: "$day"} }}
])
现在 days
是字符串。正如我之前指出的,如果排序对您很重要,那么最好的方法是像已经完成的那样投影到文档类型中并按数字键排序。当然,为了简洁起见,可以将转换日期的 $project 缠绕到 $group 阶段,这可能是您在处理整个文档时想要做的。
关于mongodb - 类似于sql中的组连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21693349/