代码之家  ›  专栏  ›  技术社区  ›  Michel El Hajj

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

  •  -1
  • Michel El Hajj  · 技术社区  · 7 年前

    我在我的蒙古数据库中有类似的记录。我需要找到2017年1月1日到2018年4月30日之间的所有用户数量,并按月进行排序。

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

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

    2 回复  |  直到 7 年前
        1
  •  0
  •   dnickless    7 年前

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

    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
        }
    }])
    
        2
  •  0
  •   King of Hentai    7 年前

    也许这对你有帮助:

    db.YOURCOLLECTION.find({
    created: {
        '$gte': new Timestamp(new Date(2017, 01, 01), 0),
        '$lte': new Timestamp(new Date(2017, 04, 30), 0)
    }})
    

    把你的收藏换成你的收藏,它会起作用的。