To convert the string to date in MongoDB, use the following syntax:
db.yourCollectionName.aggregate( [ { $project: { anyVariableName: { $dateFromString: { dateString: '$yourFieldName’ } } } } ] );
To understand the above syntax, let us create a collection with some documents. The query to create a collection with documents are as follows:
> db.ConvertStringToDateDemo.insertOne({"ArrivalDate":"20-10-2019"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ef3596fd07954a489069f") } > db.ConvertStringToDateDemo.insertOne({"ArrivalDate":"21-02-2019"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ef3616fd07954a48906a0") } > db.ConvertStringToDateDemo.insertOne({"ArrivalDate":"10-12-2018"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ef36d6fd07954a48906a1") } > db.ConvertStringToDateDemo.insertOne({"ArrivalDate":"31-01-2017"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ef37b6fd07954a48906a2") }
Display all documents from a collection with the help of find() method. The query is as follows:
> db.ConvertStringToDateDemo.find().pretty();
The following is the output:
{ "_id" : ObjectId("5c6ef3596fd07954a489069f"), "ArrivalDate" : "20-10-2019" } { "_id" : ObjectId("5c6ef3616fd07954a48906a0"), "ArrivalDate" : "21-02-2019" } { "_id" : ObjectId("5c6ef36d6fd07954a48906a1"), "ArrivalDate" : "10-12-2018" } { "_id" : ObjectId("5c6ef37b6fd07954a48906a2"), "ArrivalDate" : "31-01-2017" }
Here is the query to convert string to date:
> db.ConvertStringToDateDemo.aggregate( [ { ... $project: { ... StringToDate: { ... $dateFromString: { ... dateString: '$ArrivalDate' ... } ... } ... } ... } ] ).pretty();
The following is the output:
{ "_id" : ObjectId("5c6ef3596fd07954a489069f"), "StringToDate" : ISODate("2019-10-20T00:00:00Z") } { "_id" : ObjectId("5c6ef3616fd07954a48906a0"), "StringToDate" : ISODate("2019-02-21T00:00:00Z") } { "_id" : ObjectId("5c6ef36d6fd07954a48906a1"), "StringToDate" : ISODate("2018-12-10T00:00:00Z") } { "_id" : ObjectId("5c6ef37b6fd07954a48906a2"), "StringToDate" : ISODate("2017-01-31T00:00:00Z") }