Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoTemplate pull subdocument

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.

like image 690
fernandospr Avatar asked Nov 26 '14 15:11

fernandospr


1 Answers

It seems this works:

this.mongoTemplate.updateMulti(new Query(),
        new Update().pull("tests", Query.query(Criteria.where("experiment.$id").is("MyExperiment1"))), USERS_COLLECTION_NAME);
like image 139
fernandospr Avatar answered Sep 30 '22 01:09

fernandospr