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