How to convert from string to date data type in MongoDB?


To convert from String to date data type, you need to write some script. Let us first create a collection with documents

>db.stringToDateDataTypeDemo.insertOne({"CustomerName":"Carol","ShippingDate":"2019-
01-21"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca2071d66324ffac2a7dc60")
}
>db.stringToDateDataTypeDemo.insertOne({"CustomerName":"Bob","ShippingDate":"2019-
02-24"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca2073566324ffac2a7dc61")
}
>db.stringToDateDataTypeDemo.insertOne({"CustomerName":"Chris","ShippingDate":"2019-
04-01"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca2074266324ffac2a7dc62")
}

Following is the query to display all documents from a collection with the help of find() method

> db.stringToDateDataTypeDemo.find().pretty();

This will produce the following output

{
   "_id" : ObjectId("5ca2071d66324ffac2a7dc60"),
   "CustomerName" : "Carol",
   "ShippingDate" : "2019-01-21"
}
{
   "_id" : ObjectId("5ca2073566324ffac2a7dc61"),
   "CustomerName" : "Bob",
   "ShippingDate" : "2019-02-24"
}
{
   "_id" : ObjectId("5ca2074266324ffac2a7dc62"),
   "CustomerName" : "Chris",
   "ShippingDate" : "2019-04-01"
}

Following is the query to convert String to date data type

> db.stringToDateDataTypeDemo.find().forEach(function(data){
...    data.ShippingDate= ISODate(data.ShippingDate);
...    db.stringToDateDataTypeDemo.save(data);
... });

Let us display all documents once again to check the string is converted to date data type or not. Following is the query

> db.stringToDateDataTypeDemo.find().pretty();

This will produce the following output

{
   "_id" : ObjectId("5ca2071d66324ffac2a7dc60"),
   "CustomerName" : "Carol",
   "ShippingDate" : ISODate("2019-01-21T00:00:00Z")
}
{
   "_id" : ObjectId("5ca2073566324ffac2a7dc61"),
   "CustomerName" : "Bob",
   "ShippingDate" : ISODate("2019-02-24T00:00:00Z")
}
{
   "_id" : ObjectId("5ca2074266324ffac2a7dc62"),
   "CustomerName" : "Chris",
   "ShippingDate" : ISODate("2019-04-01T00:00:00Z")
}

Updated on: 30-Jul-2019

601 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements