如何在mongodb中转换日期格式 [英] How to convert date format in mongodb

查看:536
本文介绍了如何在mongodb中转换日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用API​​(因此我无法控制这些字段) - 其中一个字段的类型为 Date

I am using an API (so I have no control over the fields) - one of the fields is of type Date.

现在,我发现存储在记录中的日期类似于以下值:

Now, I find that the date stored in the records resembles the following value:

{
    ...
    "foobarDate": "2013-05-26T05:00:00.000Z",
    ...
}

现在我想根据这个日期检索一些记录 - 例如,我需要检索所有 fooBarDate 早于今天的日期。

Now I wish to retrieve some records based on this date - for example, I need to retrieve all the records whose fooBarDate is earlier than today's date.

如果我使用Javascript的 Date()功能,然后以下列格式获取日期:

Wed Jun 19 2013 21:13:50 GMT + 0530(IST)

If I use Javascript's Date() functionality, then I get the date in the following format:
Wed Jun 19 2013 21:13:50 GMT+0530 (IST)

如果我尝试设计我的查询如下...

If I try to design my query as follows...

{
    "fooBarDate": {
        "$lte": <the date calculated in javascript>
    }
}

...我没有得到记录 - 我得到一个空数组 - 我怀疑是由于存储在MongoDB中的日期格式与我传递的格式不同的原因。

...I do not get the records - I get an empty array - I suspect it is due the reason that the format of the Date stored in MongoDB is different from the one I am passing.

如何转换Javascript日期格式到mongodb格式?或者至少,如何以MongoDB中存储的格式获取当前日期?

How to convert the Javascript date format to the mongodb format? Or at least, how do I get the current date in the format stored in MongoDB?

P.S。我正在使用nodeJs并希望在这种情况下查询DB。

P.S. I am using nodeJs and wish to query the DB in this case.

推荐答案

Mongo将日期存储为 ISODate 对象。只需将我们的日期包裹到 ISODate 构造函数中:

Mongo stores dates as ISODate objects. Just wrap our date into ISODate constructor:

{
    "fooBarDate": {
        "$lte": ISODate("2013-05-26T05:00:00.000Z")
    }
}

这篇关于如何在mongodb中转换日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆