如何在MongoDB集合中查询ISO日期存储在字符串字段中的日期

如何在MongoDB集合中查询ISO日期存储在字符串字段中的日期

本文介绍了如何在MongoDB集合中查询ISO日期存储在字符串字段中的日期范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景:考虑我有一个名为MyCollection的集合,其中包含以下数据:

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"
}

现在,我想查询MongoDB数据库,其中上述类型的数据存在于大量文档中.我的查询基于日期范围,即使用$gt$gte$lt& $lte

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

考虑以上示例,预期结果是,查询必须获取一个文档(因为"CreatedTime":"2013-12-01T14:35:00Z"大于在查询"2013-05-25T09中传递的值: 29:40.572Z');而不是,问题在于字段CreatedTime是字符串格式.

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?

推荐答案

您可以像在示例中一样进行查询.

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.

这篇关于如何在MongoDB集合中查询ISO日期存储在字符串字段中的日期范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 13:39