有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在mongodb按查询范围过滤方面遇到的问题

我对mongodb有意见。有人能解释一下为什么这样做(给出了一些结果):

db.getCollection('test').find({"reportedOn" : { "$gte" :    ISODate("2019-03-01T01:20:00"), "$lt" : ISODate("2019-04-01T02:00:00") } });

这不起作用(返回零):

db.getCollection('test').find({"reportedOn" : { "$gte" : { "$date" : 1551398400000 }, "$lt" : { "$date" : 1554073200000 } } });

非常感谢


共 (2) 个答案

  1. # 1 楼答案

    您可能需要检查这种related topic来理解为什么您实际上不能在查询中直接使用纪元时间

    以下是查询日期的有趣部分:

    根据Data Types in the mongo Shell的说法,两者应该是等价的:

    The mongo db provides various methods to return the date, either as a string or as a Date object:

    • Date() method which returns the current date as a string.
    • new Date() constructor which returns a Date object using the ISODate() wrapper.
    • ISODate() constructor which returns a Date object using the ISODate() wrapper.

    以及使用ISODateshould still return a Date object

    {"$date": "ISO-8601 string"}可以在需要严格的JSON表示时使用

    因此,您可能需要检查all ISO-8601 available formats,并根据预期的格式相应地更新代码,以使其按预期工作

  2. # 2 楼答案

    请尝试以下查询

    { "$date" : { "$numberLong" : "<dateAsMilliseconds>" } }
    

    正如MongoDB文档中提到的,而不是仅与$date进行比较Link