V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
dbsg
V2EX  ›  问与答

问一个 mongo 查询语句

  •  
  •   dbsg · 2018-03-23 12:00:10 +08:00 · 1046 次点击
    这是一个创建于 2197 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我 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 }

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

    1 条回复    2018-03-23 12:17:13 +08:00
    egen
        1
    egen  
       2018-03-23 12:17:13 +08:00
    按天统计 设置 $group._id = { year: { $year: '$time'}, month: { $month: '$time'}, day: { $dayOfMonth: '$time'} };
    最后 id 格式可以用 $project 来调整
    没数据的聚合后手动添加吧
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3085 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 55ms · UTC 12:52 · PVG 20:52 · LAX 05:52 · JFK 08:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.