【问题标题】:Query mongo with operator or使用运算符或查询 mongo
【发布时间】:2019-05-13 17:30:10
【问题描述】:

如果参数为空 - 获取所有对象,如果参数不为空 - 获取带参数的对象。 我有疑问:

@Query("{$and : [{$or : [ { $where: '?0 == null' } , { topic : ?0 }]}] }")
    List<Event> find(Topic topic);

在我使用 topic = Topic.SPORT 运行方法时,我得到:

抛出异常[请求处理失败;嵌套异常是 org.springframework.data.mongodb.UncategorizedMongoDbException:查询 失败,错误代码 16722 和错误消息“ReferenceError: SPORT 在服务器 localhost:27017 上未定义;嵌套异常是 com.mongodb.MongoQueryException:查询失败,错误代码 16722 和服务器上的错误消息“ReferenceError:SPORT 未定义” localhost:27017] 根本原因

但是如果我用 topic = null 运行这个方法,我会得到所有对象(这是真的)

我重构了这个方法,如下图:

@Query("{$and : [{$or : [ { $where: '\"?0\" == null' } , { topic : ?0 }]}] }")
    List<Event> find(Topic topic);

我可以使用参数 topic = Topic.SPORT 获取对象,但我无法获取 topic = null 的所有对象,我得到的是空列表。 我该如何解决这个问题?

【问题讨论】:

  • 我相信您需要在{ topic : ?0 } 中的?0 周围加上引号
  • @Bajal 如果 topic = null,我想让 List 独立于主题(这是我的参数)
  • 默认情况下,mongorepository 使用 所以可以去掉第一个$and

标签: mongodb spring-data spring-data-mongodb


【解决方案1】:

要解决您的问题,您应该先检查一下。 1. 主题查询 主题:?0 2.如果为空~>真 $where: '\"?0\" == null' 这是您的方法,但我们还有其他方法可以在 mongodocument (https://docs.mongodb.com/manual/tutorial/query-for-null-fields/) 中找到:

db.inventory.find( { item : { $type: 10 } } )
db.inventory.find( { item : { $exists: false } } )

$type: 10 使用 go 你把这个字段保存为 null 和 $exit 检查此字段是否可用。

之后,我们得到了 $or 的组合。 希望你做得好

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 2015-03-25
    • 2017-03-25
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多