Find oldest/youngest post in mongodb collection

user3799658 picture user3799658 · Feb 10, 2015 · Viewed 13.1k times · Source

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.

Answer

wdberkeley picture wdberkeley · Feb 10, 2015

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.