MongoDB: Pull using Java Driver
arrays, mongodb, mongodb-java, mongodb-query
Solution
Try this:
`Bson delete = Updates.pull("scores", new Document("SE", 96));`
Problem
Here I am learning MongoDB. And I am stuck at performing a very basic operation using the MongoDB Java driver. I am trying to remove an element from an array present in the document. The document looks like this: ``` db.test.find().pretty() { "_id" : ObjectId("581245dd51030d389f5cf701"), "name" : "Rahul", "scores" : [ { "SDM" : 97 }, { "SE" : 96 }, { "DM" : 80 } ] } ``` I am trying to remove the second element in the array i.e. `{"SE" : 96}`. I understand that I can achieve this using `coll.update(match, new BasicDBObject("$pull", update));`. However I would like to leverage the `com.mongodb.client.model.Updates.pull(final String fieldName, final TItem value)`method. This is what I tried before posting the question: 1) I expected nothing to happen when I tried this and indeed there was no modification to the document. ``` ` Bson filter = Filters.eq("name", "Rahul"); Bson delete = Updates.pull("SE", 96); collection.updateOne(filter, delete);` ``` 2) The following is throwing an exception. ``` ` Bson filter = Filters.eq("name", "Rahul"); Bson delete = Updates.pull("scores.SE", 96); collection.updateOne(filter, delete);` ``` Exception: ``` Exception in thread "main" com.mongodb.MongoWriteException: cannot use the part (scores of scores.SE) to traverse the element ({scores: [ { SDM: 97.0 }, { SE: 96.0 }, { DM: 80.0 } ]}) at com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:523) at com.mongodb.MongoCollectionImpl.update(MongoCollectionImpl.java:508) at com.mongodb.MongoCollectionImpl.updateOne(MongoCollectionImpl.java:355) at com.mongodb.MongoCollectionImpl.updateOne(MongoCollectionImpl.java:350) at com.mongodb.mongoProject.crud.UpdateTest.main(HW_3_1.java:30) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) ``` Please let me know where am I going wrong with this. Thanks...