带有下划线char的属性上的Spring mongo查询集合

时间:2017-02-16 10:49:10

标签: java spring mongodb underscore.js mongotemplate

我使用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。

我现在真的没有想法。

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

根据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在找到多个_标记时可能不会拆分,但在解析标准时会拆分进行遍历。

相关问题