Inserting Date() in to Mongodb through mongo shell

2019-03-15 18:20发布

问题:

I am inserting document through following query:

db.collection.insert(  
{  
      date: Date('Dec 12, 2014 14:12:00')  
})  

But it will give me an error.

How can I insert a date in my collection without getting an error?

回答1:

You must be getting a different error as the code above will result in the Date() method returning the current date as a string, regardless of the arguments supplied with the object. From the documentation: JavaScript Date objects can only be instantiated by calling JavaScript Date as a constructor: calling it as a regular function (i.e. without the new operator) will return a string rather than a Date object; unlike other JavaScript object types, JavaScript Date objects have no literal syntax.

You might want to try this instead to get the correct date, bearing in mind that the month parameter of JavaScript's Date constructor is 0-based:

var myDate = new Date(2014, 11, 12, 14, 12);
db.collection.insert({ "date": myDate });


回答2:

JavaScript date objects can be a funny thing. Depending on how you actually supply the arguments to instantiate them you get different results.

For example, some might suggest you try this:

var myDate = new Date(2014, 11, 12, 14, 12)

Which seems fine, but there is a problem.

You see that some forms of instantiating a Date object in JavaScript use the "local" timezone when creating the date. Others use the UTC or "universal" time zone to a set standard. This is also the "standard" that MongoDB expects, and is generally accepted as best practice for your application to store dates in this way. Do any conversions in your code, away from the data store. This ensures you can deal with multiple locales without issue.

So what you should be doing is this:

var date = new Date("2014-12-11T14:12:00Z")

There is also a "helper" in the MongoDB shell that handles this pretty much in the same way, but more specific to the syntax:

var date = new ISODate("2014-12-11T14:12:00Z")

This produces a UTC Date value that stores correctly as expected. You should always deal with UTC when storing dates in MongoDB.