json 如何查询 MongoDB 集合上的日期范围,其中 ISO 日期存储在字符串字段中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16748332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to query date range on the MongoDB collection where the ISO date is stored in string field?
提问by Amol M Kulkarni
Scenario: Consider I am having a collection called MyCollection, with following data:
场景:假设我有一个名为 的集合MyCollection,其中包含以下数据:
{
"_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
现在我想查询 MongoDB 数据库,其中上述类型的数据存在于大量文档中。我的查询基于日期范围,即使用$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 CreatedTimeis in string format.
考虑到上面的例子,预期的结果是,查询必须得到一个文档(因为 "CreatedTime" : "2013-12-01T14:35:00Z" 大于在查询 '2013-05-25T09:29:40.572 中传递的值Z'); 而不是,问题是该字段CreatedTime是字符串格式。
Question: Is there any way so that I can get my expected result perfectly without changing the string field type to date?
问题:有什么方法可以让我在不更改字符串字段类型的情况下完美获得预期结果?
采纳答案by Asya Kamsky
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.
字符串排序是一致的,会给你你想要的确切关系。

![JSON.stringify 返回“[object Object]”而不是对象的内容](/res/img/loading.gif)