Updating an array in MongoDB using Java driver
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 contai开发者_JAVA百科ns 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!
Oliveryes, 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!
精彩评论