![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert date parts to date in MongoDB
Let us first create a collection with documents −
> db.demo386.insert( ... { ... details: { Month: 02, Day: 27, Year: 2020 } ... } ... ); WriteResult({ "nInserted" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo386.find();
This will produce the following output −
{ "_id" : ObjectId("5e5bd9a222064be7ab44e7f7"), "details" : { "Month" : 2, "Day" : 27, "Year" : 2020 } }
Following is the query to convert date parts to date −
> db.demo386.aggregate( ... {"$project":{ ... "_id":0, ... "DueDate":{ ... "$dateToString":{ ... "format":"%m-%d-%Y", ... "date":{"$dateFromParts": {"year":"$details.Year","month":"$details.Month","day":"$details.Day"}} ... } ... } ... }} ... );
This will produce the following output −
{ "DueDate" : "02-27-2020" }
Advertisements