2017-02-15 114 views
1

我使用貓鼬像這樣從MongoDB的結果:MongoDB的骨料和組嵌套場

{ 
"_id" : { "$oid" : "589f926267d836193b0773fd"} , 
"id" : "3" , 
"update_date" : "2017-02-11" ,  

"data": 
[{ 
"groupx" : 3 , 
"speed" : 40 , 
"lon" : "-6.242747" , 
"lat" : "34.821839" , 
"update_timestamp" : "1486852706749" , 
"date" : { "$date" : 1486852706749} 
} , 
{ 
"groupx" : 3 , 
"speed" : 120 , 
"lon" : "-6.7515" , 
"lat" : "33.96547" , 
"update_timestamp" : "1486852718771" , 
"date" : { "$date" : 1486852714771} 
} , 
{ 
"groupx" : 4 , 
"speed" : 100 , 
"lon" : "-6.9515" , 
"lat" : "33.958047" , 
"update_timestamp" : "1486852714771" , 
"date" : { "$date" : 1486852714771} 
} , 
{ 
"groupx" : 4 , 
"speed" : 80 , 
"lon" : "-6.92915" , 
"lat" : "33.928047" , 
"update_timestamp" : "1486852980615" , 
"date" : { "$date" : 1486852980615 
} 
}]  
} 

我想組對象由「groupx」以及每個groupx得到平均速度和總時間花費。

我用骨料是這樣的:

myModel.aggregate([ 
    { $match: {$and: rules } }, 
    { 
     $project: { 
      _id: 0, 
      groupA: '$data.groupx', 
      speedA: '$data.speed', 
      dateA: '$data.date' 
     }}, 
    { $group: { 
     _id: '$groupA', 
     minDate: { $min: '$dateA'}, 
     maxDate: { $max: '$dateA'}, 
     avg_speed: { $avg: '$speedA'}, 
    }} 
]).exec(function (e, d) { 
console.log(d) 
}); 

請,如果有人可以幫助完成這個查詢。

//Desired result: 

{ 
_id: 
group:3 
avg_speed:80 
time_spent:19223556 //diff between min and max date in group 3 

}, 
{ 
_id: 
group:4 
avg_speed:9 
time_spent:19223556 //diff between min and max date in group 4 

} 
... 

謝謝你,對不起我的英文。

+0

在項目階段之前添加'{$ unwind:「$ data」}'階段。 – Veeram

+0

[MongoDB中的$ unwind運算符是什麼?](http://stackoverflow.com/questions/16448175/whats-the-unwind-operator-in-mongodb) – Veeram

回答

0

我回答我自己:)

這也許可以幫助某人。

... 
var id = req.params.id; 
var rules = [{'_id' : id}]; 

{ $match: {$and: rules } }, 
    { $unwind : "$data" }, 
    { $project: { 
      _id: 0, 
      groupA: '$data.groupx', 
      speedA: '$data.speed', 
      dateA: '$data.date' 
     }}, 
    { $group: { 
     _id: '$groupA', 
     avgSpeedB: { $avg: '$speedA'}, 
     minDate: { $min: '$dateA'}, 
     maxDate: { $max: '$dateA'}, 
    }}, 
    { $project: { 
      _id: 1, 
      debutB: '$minDate', 
      tempsSpentB: {$subtract: [ '$maxDate','$minDate']}, 
      distanceB: { $multiply: [ '$avgSpeedB',{$subtract: [ '$maxDate','$minDate']}]}, 
      avgSpeedB:1 

    }}.exec(function (e, d) { 

     console.log(d); 

    });