我正试着用线束和日期将所有的记录分组。然后显示该日期的总持续时间。
文档结构
const testResultsSchema = new Schema({
duration: Number,
status: Boolean,
start_date: Date,
end_date: Date,
harness: String
});查询我正在运行:db.ecommresults.aggregate(
[
{ $project :
{
_id: 0,
harness: 1,
duration: 1,
end_date: 1
}
},
{ $group :
{
_id: { harness: "$harness", testDay: { $dateToString: { format: "%Y-%m-%d", date: "$end_date" } } },
"total_time" : { $sum: "$duration" }
}
}
]).pretty();我正在接收以下输出
{
"_id" : {
"harness" : "api",
"testDay" : "2018-03-11"
},
"total_time" : 120
}
{
"_id" : {
"harness" : "api",
"testDay" : "2018-03-10"
},
"total_time" : 120
}
{
"_id" : {
"harness" : "api",
"testDay" : "2018-03-12"
},
"total_time" : 33
}
{
"_id" : {
"harness" : "selenium",
"testDay" : "2018-03-11"
},
"total_time" : 306
}输出的格式不是我想要的,我想要的是类似于的东西
"api" {
{ "testDay: "2018-03-11", "total_time": 306 }
{ "testDay: "2018-03-12", "total_time": 542 }
},
"selenium" {
{"testDay: "2018-03-11", "total_time": 645 },
{"testDay: "2018-03-16", "total_time": 444 }
}
}我正在使用这个节点,快递,猫鼬,然后使用响应在一个反应应用程序。为了便于在客户端使用,我希望发送格式化的数据。
我对mongo非常陌生(实际上,我尝试使用的所有堆栈)。
发布于 2018-03-14 07:12:50
Mongodb目前不支持动态字段,因此需要将其包含在指定的字段中。我已经添加了片段,看看它是否适合你。
db.getCollection('groupby').aggregate([
{ "$sort": { "end_date": 1 } },
{"$group":{
"_id":{"harness":"$harness","testDay":"$end_date"},
"total_time":{"$sum":"$duration"}
}},
{"$group":{
"_id":"$_id.harness",
"v":{"$push":{"testDay":"$_id.testDay","total_time":"$total_time"}}
}},
{"$group": {
"_id": "",
"data": {"$push": "$$ROOT"}
}
}
])它的输出是这样的
{
"_id" : "",
"data" : [
{
"_id" : "api",
"v" : [
{
"testDay" : "2018-02-23",
"total_time" : 60
},
{
"testDay" : "2018-02-24",
"total_time" : 180
}
]
},
{
"_id" : "selenium",
"v" : [
{
"testDay" : "2018-02-21",
"total_time" : 30
},
{
"testDay" : "2018-02-24",
"total_time" : 30
}
]
}
]
}希望能帮上忙。
发布于 2018-03-14 04:21:02
您可以使用下面的代码获得您想要的3.4格式。
添加额外的$group以获得值,然后使用$replaceRoot和$arrayToObject将单个值数组转换为指定的键值对。
[
{"$group":{
"_id":{"harness":"$harness","testDay":"$testDay"},
"total_time":{"$sum":"$duration"}
}},
{"$group":{
"_id":"$_id.harness",
"v":{"$push":{"testDay":"$_id.testDay","total_time":"$total_time"}}
}},
{"$replaceRoot":{"newRoot":{
"$let":{
"vars":{"array":[{"k":"$_id", "v":"$v"}]},
"in":{"$arrayToObject":"$$array"}}
}}}
]https://stackoverflow.com/questions/49269444
复制相似问题