本文介绍了通过mongo shell将Date()插入Mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过以下查询插入文档:

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?

推荐答案

你必须得到一个不同的错误,因为上面的代码将导致 Date()方法返回当前日期作为字符串,无论提供的参数如何物体。来自: JavaScript日期只能通过调用JavaScript Date 作为构造函数来实例化对象:将其作为常规函数调用(即没有 new operator)将返回一个字符串而不是 Date 对象;与其他JavaScript对象类型不同,JavaScript Date对象没有文字语法。

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.

您可能想尝试这样做以获得正确的日期,请记住JavaScript的Date构造函数的month参数是从0开始的:

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 });

这篇关于通过mongo shell将Date()插入Mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 13:23