我有一个导入MongoDB的csv文件,它具有以下结构:
我希望将start与id分组,将所有其他字段分组为其子类,如:
"_id" : "A" {
"destination" : B {
"duration" : 5
"duration" : 3
"duration" : 6
}
"destination" : C {
"duration" : 10
}
}
"_id" : "B" {
"destination" : A {
"duration" : 4
}
}
我理解MongoDB聚合命令的基础知识,我试过这个基于Yogesh的答案:
db.test.aggregate([
{ "$group": {
"_id": "$start",
"Trips": {
"$push": {
"Destination" : "$destination",
"Duration" : "$duration"
}
}
}
}],{allowDiskUse:true}).pretty()
我的问题是如何将持续时间分组到那里。现在,从A到B的2次“旅行”,有2个这样的条目:
{ "Destination": B,
"Duration": 5
},
{
"EndStationID": B,
"Duration": 3
}
我怎样才能将它们组合成这样的结构:
{ "Destination": B {
"Duration": 5,
"Duration": 3
}
答案 0 :(得分:1)
根据您的CSV结构,我创建了以下集合
{ "start" : "A", "destination" : "B", "duration" : 5 }
{ "start" : "A", "destination" : "B", "duration" : 3 }
{ "start" : "A", "destination" : "B", "duration" : 6 }
{ "start" : "B", "destination" : "A", "duration" : 4 }
首先你应该group
开始和目标字段,然后将持续时间推送到数组,以便聚合查询如下:
db.collectionName.aggregate({
"$group": {
"_id": {
"start": "$start",
"dest": "$destination"
},
"duration": {
"$push": {
"duration": "$duration"
}
}
}
}, {
"$project": {
"_id": "$_id.start",
"destination": "$_id.dest",
"duration": 1
}
}).pretty()