Convert date parts to date in MongoDB

MongoDBDatabaseBig Data Analytics

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" }
raja
Published on 02-Apr-2020 13:48:40
Advertisements