Michel El Hajj
Michel El Hajj

Reputation: 204

Find the records in mongodb between two dates and group them by months

I have similar records in my mongo database. I need to find all the number of users between 01/01/2017 and 30/04/2018 and sort them by month.

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

The response should be an array of the count per month, if possible!!

Upvotes: 0

Views: 3772

Answers (2)

dnickless
dnickless

Reputation: 10918

You will need to use the aggregation framework for this kind of query like this:

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
    }
}])

Upvotes: 1

King of Hentai
King of Hentai

Reputation: 41

Maybe this is helping you:

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

Replace YOURCOLLECTION with your collection and it should work.

Upvotes: 0

Related Questions