Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get latest MongoDB record by field of datetime

I have a collection like this:

{     'datetime': some-date,     'lat': '32.00',     'lon': '74.00' }, {     'datetime': some-date,     'lat': '32.00',     'lon': '74.00' } 

How can I get the latest record from MongoDB, where the datetime is the latest one? I want only a single record.

like image 205
FarazShuja Avatar asked Feb 23 '14 17:02

FarazShuja


People also ask

How do I capture a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});


1 Answers

Use sort and limit:

db.col.find().sort({"datetime": -1}).limit(1) 
like image 85
Chris Seymour Avatar answered Oct 10 '22 07:10

Chris Seymour