dbsg
V2EX  ›  问与答

问一个 mongo 查询语句

  •  
  •   dbsg · Mar 23, 2018 · 1624 views
    This topic created in 2992 days ago, the information mentioned may be changed or developed.

    我 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 replies    2018-03-23 12:17:13 +08:00
    egen
        1
    egen  
       Mar 23, 2018
    按天统计 设置 $group._id = { year: { $year: '$time'}, month: { $month: '$time'}, day: { $dayOfMonth: '$time'} };
    最后 id 格式可以用 $project 来调整
    没数据的聚合后手动添加吧
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5987 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 54ms · UTC 02:40 · PVG 10:40 · LAX 19:40 · JFK 22:40
    ♥ Do have faith in what you're doing.