How to query date range on the MongoDB collection where the ISO date is stored in string field?

邮差的信 提交于 2019-12-06 19:56:47

问题


Scenario: Consider I am having a collection called MyCollection, with following data:

{
    "_id" : 'MyUniqueID_01'
    "CreatedTime" : "2013-12-01T14:35:00Z",
    "LastModifiedTime" : "2013-12-01T13:25:00Z"
}

Now I want to query the MongoDB database where the above mentioned kind of data is in huge number of documents. And my query is based on date range i.e. using $gt, $gte, $lt & $lte

So my query may be something like:

db.MyCollection.find({ 'CreatedTime': {$gt: '2013-05-25T09:29:40.572Z'}})

Considering the above examples the expected result is, query has to get a document (since the "CreatedTime" : "2013-12-01T14:35:00Z" is greater than value passed in query '2013-05-25T09:29:40.572Z'); whereas it not, the issue is that field CreatedTime is in string format.

Question: Is there any way so that I can get my expected result perfectly without changing the string field type to date?


回答1:


You can make the queries exactly as you did in the example.

The string ordering is consistent and will give you the exact relationship you want.



来源:https://stackoverflow.com/questions/16748332/how-to-query-date-range-on-the-mongodb-collection-where-the-iso-date-is-stored-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!