Mongodb汇总$ group并计算日期范围

时间:2019-05-15 05:58:35

标签: mongodb

我有这样的文件:

{
    "_id" : ObjectId("5cc80389c723e046f504b5a9"),
    "adddress" : "string",
    "checkIn" : "2019-04-30T08:12:57.909Z"
},

{
    "_id" : ObjectId("5cc995f5a6f3eb7c483b019f"),
    "adddress" : "string",
    "checkIn" : "2019-05-01T12:49:57.561Z"
}

我尝试过这样的凝结:

     var start = new Date("2019-04-30T08:12:57.909Z");
        var end = new Date("2019-05-01T12:49:57.561Z");
        var pipeline = [
        {
            $match: {
                checkIn: {
                    $gte: start,
                    $lte: end
                }
            }
        },
        {
            $group: {
                _id: {
                    year: {
                        $year: "$checkIn"
                    },
                    month: {
                        $month: "$checkIn"
                    },
                    day: {
                        $dayOfYear: "$checkIn"
                    }
                },
                count: {
                    $sum: 1
                }
            }
        }];

db.collections.aggregate(pipeline).toArray()

是否可以按签到日期对它们进行计数并得到如下结果:

    "_id": [{
        "checkIn": "2019-03-15T00:00:00Z",
        "count": 4
    }, {
        "checkIn": "2019-04-30T00:00:00Z",
        "count": 1
    }, {
        "checkIn": "2019-05-10T00:00:00Z",
        "count": 1
    }],

3 个答案:

答案 0 :(得分:1)

The result is shown the total number of the day.

{$project: {
  checkIn: { $dateToString: { format: '%Y-%m-%d', date: '$checkIn' } }
}},
{$group: {
  _id: '$checkIn',
  checkIn: {$first: '$checkIn'},
  count: {$sum: 1}
}},
{$sort: {checkIn: 1}}

答案 1 :(得分:0)

尝试一下:我已经测试了该查询及其功能。

db.sample.aggregate([{
    $addFields: {
      date: {
        $dateFromString: {
          dateString: "$checkIn"
        }
      }
    }
  },{
    $match: {
      date: {
        $gte: start,
        $lte: end
      }
    }
  }, 
  {
    $addFields: {
      dateString: {
        $dateToString: {
          format: "%Y-%m-%d",
          date: "$date"
        }
      }
    }
  },
  {
    $group: {
      _id: "$dateString",
      count: {
        $sum: 1
      }
    }
  }
]);

答案 2 :(得分:-1)

只需$group。在组之前添加$match条件。

db.getCollection('Test').aggregate([
{
$group:{
    _id:{ $dateFromString:{dateString: { $dateToString: { format: "%Y-%m-%d", date: "$checkIn" } }}},
    count:{$sum:1}
    }
}
])