How to get all document with max date?

Viewed 462

i'm trying to get, from my MongoDB, all documents with the higher date. My db is look like :

_id:"1"
date:"21-12-20"
report:"some stuff"

_id:"2"
date:"11-11-11"
report:"qualcosa"

_id:5fe08735b5a28812866cbc8a
date:"21-12-20"
report:Object

_id:5fe0b35e2f465c2a2bbfc0fd
date:"20-12-20"
report:"ciao"

and i would like to have a result like :

_id:"1"
date:"21-12-20"
report:"some stuff"

_id:5fe08735b5a28812866cbc8a
date:"21-12-20"
report:Object

I tried to run this script :

db.collection.find({}).sort([("date", -1)]).limit(1)

but it gives me only one document.

How can I get all the documents with the greatest date automatically?

3 Answers

Try to remove limit(1) and it's gonna work

If you add .limit(1) it's only ever going to give you one document.

Either use the answer as a query to another .find(), or you can write an aggregate query. If you data set is a modest size, I prefer the former for clarity.

max_date = list(db.collection.find({}).sort([("date", -1)])).limit(1)
if len(max_date) > 0:
    db.collection.find({'date': max_date[0]['date']})

Use an aggregation pipeline like this:

db.collection.aggregate([
   { $group: { _id: null, data: { $push: "$$ROOT" } } },
   {
      $set: {
         data: {
            $filter: {
               input: "$data",
               cond: { $eq: [{ $max: "$data.date" }, "$$this.date"] }
            }
         }
      }
   },
   { $unwind: "$data" },
   { $replaceRoot: { newRoot: "$data" } }
])  
Related