【问题标题】:Spring mongo query collection on property with underscore char带有下划线字符的属性的 Spring mongo 查询集合
【发布时间】:2017-07-05 10:24:01
【问题描述】:

我正在使用 MongoTemplate 构建一个查询以从 mongo 集合中检索元素。查询条件包含一个带下划线的属性,不知何故被替换为“._”,使查询始终返回 0 个元素。

Criteria matchingCriteria = Criteria
.where("entries").elemMatch(Criteria.where("app_id").is(appId))

查看日志,我可以看到生成的查询如下:

o.s.data.mongodb.core.MongoTemplate: find using query: { "entries" : { "$elemMatch" : { "app._id" : "5834718ab0"}}} fields: null for class: Ranking in collection: ranking

我已经尝试过使用 BasicQuery,使用 '\\' 斜线下划线,并使用 unicode “app\u005Fid”。它们都不起作用。重要的是要注意我的数据库中存在一个名为“app”的集合.

这种行为看起来不标准。当我使用另一个带下划线的属性时,值不会被替换:

Criteria matchingCriteria = Criteria .where("entries").elemMatch(Criteria.where("unique_app_id").‌​is(appId)) 

日志:

o.s.data.mongodb.core.MongoTemplate find using query: { "entries" : { "$elemMatch" : { "unique_app_id" : "1131706359"}}} fields: null for class: class Ranking in collection: ranking

entries 是一个具有以下格式的集合的数组:

{
    "instanceId" : "654ba2d16579e",
    "app_id" : "583471adb0",
    "unique_app_id" : "554577506",
    "value" : 169
 }

值得一提的是,相同的查询(没有下划线替换)在 mongo IDE(本例中为 Robomongo)中运行良好。

我正在使用 spring-boot-starter-data-mongodb 1.4.1.RELEASE。

我现在真的没有想法。

有什么建议吗?

【问题讨论】:

标签: java spring mongodb underscore.js mongotemplate


【解决方案1】:

根据此Spring Data Commons 文档的第 3.4.3 节:

由于我们将下划线视为保留字符,我们强烈建议 遵循标准的 Java 命名约定(即不使用下划线) 属性名称,而不是驼峰式大小写)。

我不相信你可以在使用 Spring 的元素名称中间使用下划线字符。手动引用以引用的集合命名。使用文档类型(单数的集合名称)后跟_id ( <document>_id )。这是唯一可以在中间使用下划线的情况。

更新:这是您所看到的确切行为的现有pull request,以及Spring 的bug tracker

在 Mongo shell 中,我可以成功执行以下查询:

> db.app.findOne({ "entries" : { "$elemMatch" : { "app_id" : "1"}}})
{
    "_id" : ObjectId("58a5bc6afa8dd4ae3097d5f7"),
    "name" : "Keith",
    "entries" : [
        {
            "instanceId" : "654ba2d16579e",
            "app_id" : "1"
        }
    ]
}

因此,也许 Spring API 在解析条件时发现多个 _ 标记时不会拆分,但 确实 在解析条件时拆分以进行遍历。

【讨论】:

  • 为原始问题添加了一些细节。
  • 有趣。如果从 mongo shell 运行查询会发生什么?
  • 检查我对我的答案的最新更新。如果您将文档从app_id 更新为app__id(两个下划线)并使用.elemMatch(Criteria.where("app__id") 更新您的查询,我很想看看Spring 的反应。很难忽视我提到的已知错误——我强烈怀疑它是罪魁祸首。
猜你喜欢
  • 1970-01-01
  • 2014-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-13
相关资源
最近更新 更多