【问题标题】:UncategorizedMongoDbException: Query failed with error code 2 and error message 'unknown top level operator: $gte'UncategorizedMongoDbException:查询失败,错误代码 2 和错误消息“未知顶级运算符:$gte”
【发布时间】:2018-04-16 04:03:22
【问题描述】:

为什么我会遇到这个异常?

javax.servlet.ServletException: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.data.mongodb.UncategorizedMongoDbException: Query failed with error code 2 and error message 'unknown top level operator: $gte' on server localhost:27017; nested exception is com.mongodb.MongoQueryException: Query failed with error code 2 and error message 'unknown top level operator: $gte' on server localhost:27017
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:146)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at org.eclipse.jetty.server.Server.handle(Server.java:564)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:317)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:279)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:110)
at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:124)
at org.eclipse.jetty.util.thread.Invocable.invokePreferred(Invocable.java:128)
at org.eclipse.jetty.util.thread.Invocable$InvocableExecutor.invoke(Invocable.java:222)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:294)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.produce(EatWhatYouKill.java:126)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:673)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:591)
at java.lang.Thread.run(Thread.java:748)

没有这个代码可以正常工作:

public List<Model> getByPeriod(String field, Date from, Date to) {
    return mongo.find(new Query(Criteria.where(field).gte(from)
            .and(field).lt(to)), getModelClass());
}

也失败了

//...
.where(field).gte(from).lt(to)//...

但类似的代码适用于其他情况。

【问题讨论】:

    标签: java database spring mongodb exception


    【解决方案1】:

    我已经试过你的代码,它适用于return mongo.find(new Query(Criteria.where(field).gte(from).lt(to)), getModelClass());

    但不适合

    return mongo.find(new Query(Criteria.where(field).gte(from).and(field).lt(to)), getModelClass());

    我得到的错误是Due to limitations of the com.mongodb.BasicDBObject, you can't add a second 'field' expression specified as 'field : { "$lt" : { "$date" : "2017-11-03T12:36:54.216Z"}}'. Criteria already contains 'field : { "$gte" : { "$date" : "2017-11-02T12:36:54.216Z"}}'.

    因此结论是从查询中删除.and(field)

    仅供参考:从 = 昨天到 = 现在对我来说。

    【讨论】:

      猜你喜欢
      • 2015-01-01
      • 2018-09-03
      • 2018-12-26
      • 1970-01-01
      • 2018-05-28
      • 2017-04-08
      • 1970-01-01
      • 2016-02-09
      • 1970-01-01
      相关资源
      最近更新 更多