Tenemos los siguientes registros en una colección:
{ "_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") } Cómo filtrar los registros más recientes por $month de campo de date como este:
{ "_id" : ObjectId("3"), "date" : ISODate("2017-03-03T00:00:00Z") } { "_id" : ObjectId("5"), "date" : ISODate("2017-03-01T00:00:00Z") }$group : agrupa por el primer día del mes del año a partir de la date y agrega documentos a la matriz data .
$sort - Ordenar por _id DESC.
$skip
$limit : toma el primer documento del resultado.
$unwind : deconstruye la matriz de data en varios documentos.
$replaceWith : reemplaza el documento con el documento de data .
db.collection.aggregate([ { $group: { _id: { "$dateFromParts": { "year": { $year: "$date" }, "month": { $month: "$date" }, "day": 1 } }, data: { $push: "$$ROOT" } } }, { $sort: { _id: -1 } }, { $skip: 0 }, { $limit: 1 }, { $unwind: "$data" }, { $replaceWith: "$data" } ])Si está utilizando el método collection.find(), use el método de clasificación junto con eso.
así: collection.find().sort({created : -1})
Si desea filtrar, mire esto una vez:
collection.find({ $expr: { $eq: [{ $month: "$date" }, 03] }});¡Espero que esto ayude!.
Si está dispuesto a usar agregaciones, puede usar
$month para obtener el mes a partir de la fecha$match para filtrar el valor$sort para ordenar por ASC o DESC$project para mantener o eliminar camposaquí está el código
db.collection.aggregate([ { "$addFields": { month: { $month": "$date"} } }, { "$match": { month: 3 } }, { "$sort": { date: 1}}, { "$project": { date: 1 } } ])