使用ObjectID的Spring Data Mongo自定义存储库查询

Wha*_*les 6 java spring spring-mvc mongodb spring-data-mongodb

我有一个要实现为Spring Mongo存储库的mongo查询

db.collection.find({ 'items': 
    { $elemMatch: { 
        'refund.$id' :  ObjectId('5638cab2e4b07ff212618d7e') 
        } 
    }
}) 
Run Code Online (Sandbox Code Playgroud)

我的存储库界面是

@Query("{ 'items': { $elemMatch: { 'refund.$id' :  ObjectId(?0) } } }")
RMA findRMAByItemRefund(String refundId);
Run Code Online (Sandbox Code Playgroud)

抛出JSONParseException

Caused by: com.mongodb.util.JSONParseException: 
{ 'items': { $elemMatch: { 'refund.$id' :  ObjectId("_param_0") } } }
                                       ^
    at com.mongodb.util.JSONParser.parse(JSON.java:216)
Run Code Online (Sandbox Code Playgroud)

小智 3

尝试这个

@Query("{ 'items': { $elemMatch: { 'refund.id' :  ?0 } } }")
RMA findRMAByItemRefund(String refundId);
Run Code Online (Sandbox Code Playgroud)

根据我的经验,?0应该独立而不是用作 mongo 函数参数。

另外,是$id您自己的假设还是该字段实际上存储为$id. 如果没有,我会一起去refund.id