在mongodb中查找两个日期之间的记录并按月分组

米歇尔·埃尔·哈吉

我的 mongo 数据库中有类似的记录。我需要找到 01/01/2017 和 30/04/2018 之间的所有用户数量,并按月对它们进行排序。

{
 "id": "XV6789",
 "valid": true,
 "MobileNo": "8612636",
 "active": true,
 "created": ISODate('2018-04-18T08:28:01.778Z')
}

如果可能,响应应该是每月计数的数组!!

无情的

您将需要对此类查询使用聚合框架,如下所示:

db.collection.aggregate([{
    $match: { // filter to limit to whatever is of importance
        "created": {
            $gte: ISODate('2017-01-01T00:00:00.000Z'),
            $lte: ISODate('2018-04-30T00:00:00.000Z')
        }
    }
}, {
    $group: { // group by
        _id: {
            "month": { $month: "$created" }, // month
            "year": { $year: "$created" } }, // and year
        "count": { $sum: 1 }  // and sum up all documents per group
    }
}])

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章