MongoDB聚合和分组嵌套字段
Posted
技术标签:
【中文标题】MongoDB聚合和分组嵌套字段【英文标题】:MongoDB aggregate and group nested field 【发布时间】:2017-02-15 02:13:13 【问题描述】:我有一个使用 mongoose 的 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
...
谢谢你,对不起我的英语。
【问题讨论】:
在项目阶段之前添加$unwind:"$data"
阶段。
What's the $unwind operator in MongoDB?的可能重复
【参考方案1】:
我回答我自己:)
这也许可以帮助某人。
...
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 );
);
【讨论】:
以上是关于MongoDB聚合和分组嵌套字段的主要内容,如果未能解决你的问题,请参考以下文章