How to query objects with the longest time period in MongoDB?


Let us create a collection with documents −

> db.demo344.insertOne({"startDate":"2020-02-24 10:50:00", "endDate":"2020-02-24 11:50:00"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e53f52cf8647eb59e5620aa")
}
> db.demo344.insertOne({"startDate":"2020-02-24 08:00:00", "endDate":"2020-02-24 11:50:50"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e53f53df8647eb59e5620ab")
}

Display all documents from a collection with the help of find() method −

> db.demo344.find();

This will produce the following output −

{ "_id" : ObjectId("5e53f52cf8647eb59e5620aa"), "startDate" : "2020-02-24 10:50:00", "endDate" : "2020-02-24 11:50:00" }
{ "_id" : ObjectId("5e53f53df8647eb59e5620ab"), "startDate" : "2020-02-24 08:00:00", "endDate" : "2020-02-24 11:50:50" }

Following is how to query objects with the longest time period −

> db.demo344.aggregate([
...    { $addFields: {
...       longestTime: { $subtract: [ { $toDate: "$endDate" }, { $toDate: "$startDate" } ] }
...    } },
... { $sort: { longestTime: -1 } },
... { $limit: 1 }
... ])

This will produce the following output −

{ "_id" : ObjectId("5e53f53df8647eb59e5620ab"), "startDate" : "2020-02-24 08:00:00", "endDate" : "2020-02-24 11:50:50", "longestTime" : NumberLong(13850000) }

Updated on: 02-Apr-2020

100 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements