Search code examples
javamongodbmongodb-java

Remove childnodes in mongodb java


I have a collection where it contains child nodes of contact numbers as below.

{"username":"abc",
"email": "[email protected]",
"contact":[
            {"number":"4763485364","type":"mobile"},
            {"number":"4535345345","type":"home"}
          ]}

its a repeating set and I want to know how can I remove or change the specific number in the child node based on the type using the mongodb Java driver. I was able to remove the entire element using the BasciDBObject with the find method in the collection. But I want to remove only one number ("home" type) from the child node for the specific user. Can someone show me a sample code in java how can it be done?


Solution

  • You can use $pull to remove an item from the array.

    collection.update(new BasicDBObject("username","abc"), new BasicDBObject("$pull", new BasicDBObject("comments", new BasicDBObject("type","home"))));
    

    This code will pull the element from the comments array that matches the criteria type = "home", from the item in the collection that matches the criteria username ="abc".

    Hope this helps.