7

i tried to remove an embedded document without succcess. I'm looking for the java way of following instruction:

db.games.update({'_id': 73}, {$pull: {'goals': {'goal': 4}}})
hehe
  • 227
  • 5
  • 15
  • are you trying to remove? $unset is the command for removing the document. I am assuming you mean deleting a sub document. – hellboy Apr 05 '14 at 05:04

2 Answers2

10

The Java documentation is pretty clear, you are just constructing BSON objects to match their respective JSON counterparts as used in the shell:

    BasicDBObject query = new BasicDBObject("_id", 73);
    BasicDBObject fields = new BasicDBObject("goals", 
        new BasicDBObject( "goal", 4));
    BasicDBObject update = new BasicDBObject("$pull",fields);

    games.update( query, update );
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
4

Using Bson is similar.

Bson query = new Document().append("_id", 73);
Bson fields = new Document().append("goals", new Document().append( "goal", 4));
Bson update = new Document("$pull",fields);

games.updateOne( query, update );
Rodrigo Villalba Zayas
  • 5,326
  • 2
  • 23
  • 36
HenioJR
  • 604
  • 1
  • 10
  • 17