
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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) }
Advertisements