We have the following records in a collection:
{ "_id" : ObjectId("1"), "date" : ISODate("2017-02-01T00:00:00Z") }
{ "_id" : ObjectId("2"), "date" : ISODate("2017-02-01T00:00:00Z") }
{ "_id" : ObjectId("3"), "date" : ISODate("2017-03-03T00:00:00Z") }
{ "_id" : ObjectId("4"), "date" : ISODate("2017-02-02T00:00:00Z") }
{ "_id" : ObjectId("5"), "date" : ISODate("2017-03-01T00:00:00Z") }
{ "_id" : ObjectId("6"), "date" : ISODate("2017-02-01T00:00:00Z") }
{ "_id" : ObjectId("7"), "date" : ISODate("2017-01-02T00:00:00Z") }
{ "_id" : ObjectId("8"), "date" : ISODate("2017-01-03T00:00:00Z") }
How to filter the most recent records by $month
of date
field like this:
{ "_id" : ObjectId("3"), "date" : ISODate("2017-03-03T00:00:00Z") }
{ "_id" : ObjectId("5"), "date" : ISODate("2017-03-01T00:00:00Z") }
3
Answers
If you’re using collection.find() method, use sort method along with that.
like this :
collection.find().sort({created : -1})
If you want to filter, the look at this once :
Hope this helps!.
$group
– Group by the first day of the month year fromdate
and add documents intodata
array.$sort
– Sort by_id
DESC.$skip
$limit
– Take the first document from the result.$unwind
– Deconstruct thedata
array to multiple documents.$replaceWith
– Replace the document withdata
document.Sample Mongo Playground
If you are willing to use aggregations, you can use
$month
to get the month from date$match
to filter the value$sort
to sort by ASC or DESC$project
to keep or remove fieldshere is the code
Working Mongo playground