MongoTemplate pull subdocument

I need to output a subdocument in MongoTemplate, but cannot figure out how to do this.

My saved document:

{
    "_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 those tests that have MyExperiment1 in them. Running the following command works:

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

How do I write this using Spring MongoTemplate?

I tried the following but it does not work:

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

Thank.

+7
source share
2 answers

This seems to work:

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

Another solution that works great for me is to use the param method BasicDBObjectin it . See How to encode Spring MongoDB data for db.test.update ({name: 'abc'}, {$ pull: {'child': {'age': 10}}})pullvalue

0
source

All Articles