New date from string in MongoDB 3.4

418 views
Skip to first unread message

Srihari Prabhakar

unread,
Oct 1, 2018, 8:14:59 AM10/1/18
to mongodb-user
I have a collection in which date is stored as String

> db.datePoc.find()
{ "_id" : ObjectId("5bb20ccb9149a807d0d4d36f"), "date" : "2018-10-01T06:31:30.278Z" }

When I try to convert the date field into ISODate in the aggregation pipeline, it doesn't work as expected.

> db.datePoc.aggregate([{
...   $project: {
...     _id: 1,
...     date_iso: new Date("$date")
...   }
... }])
{ "_id" : ObjectId("5bb20ccb9149a807d0d4d36f"), "date_iso" : ISODate("1970-01-01T00:00:00Z") }


When I pass the date string directly, instead of referring to the field, it returns the result properly

> db.datePoc.aggregate([{
...   $project: {
...     _id: 1,
...     date_iso: new Date("2018-10-01T06:31:30.278Z")
...   }
... }])
{ "_id" : ObjectId("5bb20ccb9149a807d0d4d36f"), "date_iso" : ISODate("2018-10-01T06:31:30.278Z") }


Why is the behavior different in the two cases? Is there any workaround for this?


Thanks in advance...

Mailon Berni

unread,
Oct 1, 2018, 10:38:56 AM10/1/18
to mongodb-user
Hi,

trade 
date_iso: new Date("$date")
 or
 date_iso: new Date("$data")

Robert Cochran

unread,
Oct 1, 2018, 8:35:14 PM10/1/18
to mongodb-user
Hi!

Your question makes me recall a suggestion that Wan made a few weeks ago, in response to a different question. This solution works for MongoDB version 4, and all the credit goes to Wan, not to me.

use prabhakar

dateConversionStage = {

  "$addFields" : {

     "convertedDatee" : { "$convert" : { "input" : "$my_dte", "to" : "date", "onError" : "Error", "onNull" : ISODate() } }

  }

}

db.datepoc.aggregate( [ 

  dateConversionStage

  ]

)


Here is the result of executing this in the mongo shell:

mongo < convert_dates.js

MongoDB shell version v4.0.2

connecting to: mongodb://127.0.0.1:27017

MongoDB server version: 4.0.2

switched to db prabhakar

{

"$addFields" : {

"convertedDatee" : {

"$convert" : {

"input" : "$my_dte",

"to" : "date",

"onError" : "Error",

"onNull" : ISODate("2018-10-02T00:22:23.972Z")

}

}

}

}

{ "_id" : ObjectId("5bb2b75bd90f30390eb6ea6d"), "my_dte" : "2018-10-01T06:31:30.278Z", "convertedDatee" : ISODate("2018-10-01T06:31:30.278Z") }

bye



Thanks so much

Bob

Robert Cochran

unread,
Oct 1, 2018, 8:51:55 PM10/1/18
to mongodb-user
From your subject line, you seem to be saying you are on MongoDB 3.4. That means you can't use the $dateFromString operator that was introduced in MongoDB 3.6. You might benefit from this Stack Overflow post:

I suggest that you upgrade to MongoDB 3.6 or 4.0. 

Thanks

Bob


On Monday, October 1, 2018 at 8:14:59 AM UTC-4, Srihari Prabhakar wrote:
Reply all
Reply to author
Forward
0 new messages