inkriti
inkriti

Reputation: 1665

Get the latest record from mongodb collection

I want to know the most recent record in a collection. How to do that?

Note: I know the following command line queries works:

1. db.test.find().sort({"idate":-1}).limit(1).forEach(printjson);
2. db.test.find().skip(db.test.count()-1).forEach(printjson)

where idate has the timestamp added.

The problem is longer the collection is the time to get back the data and my 'test' collection is really really huge. I need a query with constant time response.

If there is any better mongodb command line query, do let me know.

Upvotes: 143

Views: 223866

Answers (10)

Anup Singh
Anup Singh

Reputation: 323

Let Mongo create the ID, it is an auto-incremented hash

mymongo: self._collection.find().sort("_id",-1).limit(1)

Upvotes: 1

Akash Singh
Akash Singh

Reputation: 11

Mongo CLI syntax:

db.collectionName.find({}).sort({$natural:-1}).limit(1)

Upvotes: 1

ssymbiotik
ssymbiotik

Reputation: 11

This is how to get the last record from all MongoDB documents from the "foo" collection.(change foo,x,y.. etc.)

db.foo.aggregate([{$sort:{ x : 1, date : 1 } },{$group: { _id: "$x" ,y: {$last:"$y"},yz: {$last:"$yz"},date: { $last : "$date" }}} ],{   allowDiskUse:true  })

you can add or remove from the group

help articles: https://docs.mongodb.com/manual/reference/operator/aggregation/group/#pipe._S_group

https://docs.mongodb.com/manual/reference/operator/aggregation/last/

Upvotes: 1

ivanleoncz
ivanleoncz

Reputation: 10005

Yet another way of getting the last item from a MongoDB Collection (don't mind about the examples):

> db.collection.find().sort({'_id':-1}).limit(1)

Normal Projection

> db.Sports.find()
{ "_id" : ObjectId("5bfb5f82dea65504b456ab12"), "Type" : "NFL", "Head" : "Patriots Won SuperBowl 2017", "Body" : "Again, the Pats won the Super Bowl." }
{ "_id" : ObjectId("5bfb6011dea65504b456ab13"), "Type" : "World Cup 2018", "Head" : "Brazil Qualified for Round of 16", "Body" : "The Brazilians are happy today, due to the qualification of the Brazilian Team for the Round of 16 for the World Cup 2018." }
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }

Sorted Projection ( _id: reverse order )

> db.Sports.find().sort({'_id':-1})
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }
{ "_id" : ObjectId("5bfb6011dea65504b456ab13"), "Type" : "World Cup 2018", "Head" : "Brazil Qualified for Round of 16", "Body" : "The Brazilians are happy today, due to the qualification of the Brazilian Team for the Round of 16 for the World Cup 2018." }
{ "_id" : ObjectId("5bfb5f82dea65504b456ab12"), "Type" : "NFL", "Head" : "Patriots Won SuperBowl 2018", "Body" : "Again, the Pats won the Super Bowl" }

sort({'_id':-1}), defines a projection in descending order of all documents, based on their _ids.

Sorted Projection ( _id: reverse order ): getting the latest (last) document from a collection.

> db.Sports.find().sort({'_id':-1}).limit(1)
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }

Upvotes: 26

Chan15
Chan15

Reputation: 1009

If you are using auto-generated Mongo Object Ids in your document, it contains timestamp in it as first 4 bytes using which latest doc inserted into the collection could be found out. I understand this is an old question, but if someone is still ending up here looking for one more alternative.

db.collectionName.aggregate(
[{$group: {_id: null, latestDocId: { $max: "$_id"}}}, {$project: {_id: 0, latestDocId: 1}}])

Above query would give the _id for the latest doc inserted into the collection

Upvotes: 1

Abdul Alim Shakir
Abdul Alim Shakir

Reputation: 1208

My Solution :

db.collection("name of collection").find({}, {limit: 1}).sort({$natural: -1})

Upvotes: 1

dark_ruby
dark_ruby

Reputation: 7866

This will give you one last document for a collection

db.collectionName.findOne({}, {sort:{$natural:-1}})

$natural:-1 means order opposite of the one that records are inserted in.

Edit: For all the downvoters, above is a Mongoose syntax, mongo CLI syntax is: db.collectionName.find({}).sort({$natural:-1}).limit(1)

Upvotes: 64

Sam
Sam

Reputation: 41

php7.1 mongoDB:
$data = $collection->findOne([],['sort' => ['_id' => -1],'projection' => ['_id' => 1]]);

Upvotes: 2

Digits
Digits

Reputation: 2684

This is a rehash of the previous answer but it's more likely to work on different mongodb versions.

db.collection.find().limit(1).sort({$natural:-1})

Upvotes: 187

Gates VP
Gates VP

Reputation: 45277

I need a query with constant time response

By default, the indexes in MongoDB are B-Trees. Searching a B-Tree is a O(logN) operation, so even find({_id:...}) will not provide constant time, O(1) responses.

That stated, you can also sort by the _id if you are using ObjectId for you IDs. See here for details. Of course, even that is only good to the last second.

You may to resort to "writing twice". Write once to the main collection and write again to a "last updated" collection. Without transactions this will not be perfect, but with only one item in the "last updated" collection it will always be fast.

Upvotes: 20

Related Questions