20

I'm using MongoDB with the official Java driver (version 2.6.3). I have a MongoDB collection that contains shopping lists. A shopping list has the format

{ "_id" : { "$oid" : "4e2af1f43f8de96494d5271d"} ,
  "name" : "default" ,
  "items" : [ { "description" : "Cheese" , "quantity" : 1 , "unit" : "kg"} ,
              { "description" : "Water" , "quantity" : 3 , "unit" : "bottle"} ] }

Now I want to add a new item to the list with the update()method of DBCollection. But whatever I try it won't work although it's telling me

{ "updatedExisting" : true , "n" : 1 , "connectionId" : 63 , "err" :  null  , "ok" : 1.0}

My code does the following:

    BasicDBObject updateQuery = new BasicDBObject();
    updateQuery.put( "name", "default" );

    BasicDBObject updateCommand = new BasicDBObject();
    updateCommand.put( "$push", new BasicDBObject( "items", newShoppingItem ) );
    WriteResult result = shoppingLists.update( updateQuery, updateCommand, true, true );

newShoppingItem is a BasicDBObject which contains the data for the new item. I also tried to create the update() parameters with BasicDBObjectBuilder and JSON.parse() but it makes no difference.

I also had a look at other posts, tried googleing, but to no avail. What am I doing wrong?

Thanks for any help!
Oliver

Baldewin
  • 1,613
  • 2
  • 16
  • 23
  • I ran that exact code with the MongoDB 2.5.3 driver and it worked fine. Make sure you're looking in the right DB. – Justin Thomas Jul 23 '11 at 23:47
  • This was useful to me as a way of better understanding the somewhat obscure syntax in the Java driver for Mongo. Thanks! – jsh May 29 '12 at 21:44

1 Answers1

10

yes, the above code works perfectly fine. I know now where my error was. I wanted to do it bullet-proof, so I thought it would be best to use save() on the DBCollection at the end and explicitly save the shopping list DBObject:

shoppingLists.save( shoppingList );

I now read in some other forum that the objects you retrieve from the database are then not synched with the database afterwards (sounds kind of logical to me now :) ). So I overwrote the changes myself every time. After removing the line above it worked :)

So one important rule: When you update your DBCollection – this is sent directly to the database! – don't save a DBObject that you queried before the update! It will overwrite your update!

Baldewin
  • 1,613
  • 2
  • 16
  • 23