Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find oldest/youngest post in mongodb collection

Tags:

I have a mongodb collection with many fields. One field is 'date_time', which is in an ISO datetime format, Ex: ISODate("2014-06-11T19:16:46Z"), and another field is 'name'.

Given a name, how do I find out the oldest/youngest post in the collection?

Ex: If there are two posts in the collection 'data' :

[{'name' : 'John', 'date_time' : ISODate("2014-06-11T19:16:46Z")},  {'name' : 'John', 'date_time' : ISODate("2015-06-11T19:16:46Z")}] 

Given the name 'John' how do I find out the oldest post in the collection i.e., the one with ISODate("2014-06-11T19:16:46Z")? Similarly for the youngest post.

like image 227
user3799658 Avatar asked Feb 10 '15 17:02

user3799658


People also ask

How do I find the earliest date in MongoDB?

Use the $first operator to get the first record of the group, which will also be the oldest. Use the $last operator to get the last record in the group, which will also be the newest.

How do I get the last object in MongoDB?

To find last object in collection, at first sort() to sort the values. Use limit() to get number of values i.e. if you want only the last object, then use limit(1).

Where is first document in MongoDB?

MongoDB provides two methods for finding documents from a collection: findOne() - returns a the first document that matched with the specified criteria. find() - returns a cursor to the selected documents that matched with the specified criteria.


1 Answers

Oldest:

db.posts.find({ "name" : "John" }).sort({ "date_time" : 1 }).limit(1) 

Newest:

db.posts.find({ "name" : "John" }).sort({ "date_time" : -1 }).limit(1) 

Index on { "name" : 1, "date_time" : 1 } to make the queries efficient.

like image 120
wdberkeley Avatar answered Oct 31 '22 16:10

wdberkeley