2017-05-01 81 views
1

我有我导入到MongoDB的csv文件,它具有以下结构:组/聚合领域一起

enter image description here

我想组这与开始的ID,和其他所有领域作为该儿童的,就像这样:

"_id" : "A" { 
      "destination" : B { 
       "duration" : 5 
       "duration" : 3 
       "duration" : 6 
      } 
      "destination" : C { 
       "duration" : 10 
      } 
    } 
    "_id" : "B" { 
      "destination" : A { 
       "duration" : 4 
      } 
    } 

我理解的MongoDB的聚集命令的基础知识,我想这是基于约杰什的回答是:

db.test.aggregate([ 
{ "$group": { 
    "_id": "$start", 
    "Trips": { 
     "$push": { 
      "Destination" : "$destination", 
      "Duration"  : "$duration" 
     } 
    } 
    } 
}],{allowDiskUse:true}).pretty() 

我的问题是我如何也可以将持续时间分组到那里。眼下,从A 2“旅行”到B,有2项像这样:

{ "Destination": B, 
     "Duration": 5 
    }, 
    { 
     "EndStationID": B, 
     "Duration": 3 
    } 

我怎么能还结合这些成结构是这样的:

{ "Destination": B { 
      "Duration": 5, 
      "Duration": 3 
    } 

回答

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() 
+1

谢谢,我结束了使用部分你的方法结合这里的答案:http://stackoverflow.com/questions/16772156/nested-grouping-with-mongodb – ffritz