MongoTemplate pull subdocument

北城以北 提交于 2019-11-30 23:30:01

问题


I need to pull a subdocument in MongoTemplate but cannot figure out how to do it.

My saved document is:

{
    "_id" : "FooUser",
    "_class" : "com.domain.User",
    "tests" : [ 
        {
            "variant" : {
                "_id" : "C",
                "probability" : "0.5"
            },
            "experiment" : {
                "$ref" : "experiment",
                "$id" : "MyExperiment2"
            }
        }, 
        {
            "variant" : {
                "_id" : "B",
                "probability" : "0.5"
            },
            "experiment" : {
                "$ref" : "experiment",
                "$id" : "MyExperiment1"
            }
        }
    ]
}

I need to remove only the test that has MyExperiment1. Executing the following command works:

db.user.update( {}, {$pull: { "tests":{"experiment.$id":"MyExperiment1"}}}, {multi: true} )

How should I write this using Spring MongoTemplate?

I have tried the following, but does not work:

this.mongoTemplate.updateMulti(new Query(), new Update().pull("tests", "{\"experiment.$id\":\"MyExperiment1\"}"), "user");

Thanks.


回答1:


It seems this works:

this.mongoTemplate.updateMulti(new Query(),
        new Update().pull("tests", Query.query(Criteria.where("experiment.$id").is("MyExperiment1"))), USERS_COLLECTION_NAME);



回答2:


Another solution which worked fine for me is the use of a BasicDBObject into the pull method's value param. See How to code with Spring data MongoDB for db.test.update({name:'abc'}, {$pull: {'child': {'age':10}}})



来源:https://stackoverflow.com/questions/27152868/mongotemplate-pull-subdocument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!