问一个 mongo 查询语句

2018-03-23 12:00:10 +08:00
 dbsg

我 mongo 表里面的结构类似是这样的

{ time:'2018-03-10 00:00:00', number: 234, score: 123 },

{ time:'2018-03-10 12:00:00', number: 234, score: 123 },

{ time:'2018-03-11 00:00:00', number: 456, score: 345 },

{ time:'2018-03-11 00:00:00', number: 456, score: 345 }

请问我怎样可以,获取一段时间内每一天 number 和 score 的平均值,希望的输出结果是

{ _id: 2018-03-10, numberAvg: 234, scoreAvg: 123, count: 2 },

{ _id: 2018-03-11, numberAvg: 456, scoreAvg: 345, count: 2 }

用这个语句,只能一天天的查,而且_id 也不是我想要的

db.xxx.aggregate( [
{ $match : {time: { '$gte':'2018-03-10 00:00:00','$lte': '2018-03-10 24:00:00'} }},
{ $group : { _id : "id", 'numberAvg': {$avg: '$number'}, 'scoreAvg': {$avg: '$score'}, 'count': {'$sum': 1} } } ] )

用这个,_id 符合要求,但是平均值求不出来,一直显示 null,而且也不能支持一段时间,按天输出

db.xxx.aggregate( [
{ $match : {time: { '$gte':'2018-03-10 00:00:00','$lte': '2018-03-10 24:00:00'} }},
{ $project : { day : {$substr: ["$time", 0, 10] }}},
{ $group : { _id : "$day", 'numberAvg': {$avg: '$number'}, 'scoreAvg': {$avg: '$score'}, 'count': {'$sum': 1} } } ] )

但是查询数量的就可以,比如下面这个可以得到我想要的输出格式,但是平均值却求不出来,结果都是 null

db.xxx.aggregate( [ { $match : { time: { '$gte':'2018-03-09 00:00:00'} }},
{ $project : { day : {$substr: ["$time", 0, 10] }}},
{ $group : { _id : "$day", count : { $sum : 1 }, numberAvg: {$avg:'$number'}}},
{ $sort : { _id : 1 }}, ] )

而且想请问下,比如 2018-03-09 没有数据,查询结果是不会返回的,数量能否给它一个默认值 0,平均值给 null

{ _id: 2018-03-09, numberAvg: null, scoreAvg: null, count: 0 },

{ _id: 2018-03-10, numberAvg: 234, scoreAvg: 123, count: 2 },

{ _id: 2018-03-11, numberAvg: 456, scoreAvg: 345, count: 2 }

上面就是我需要的格式,给一个时间段,按天输出所有的内容。

1057 次点击
所在节点    问与答
1 条回复
egen
2018-03-23 12:17:13 +08:00
按天统计 设置 $group._id = { year: { $year: '$time'}, month: { $month: '$time'}, day: { $dayOfMonth: '$time'} };
最后 id 格式可以用 $project 来调整
没数据的聚合后手动添加吧

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/440726

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX