问题描述
我正在使用MongoDB和官方Java驱动程序(版本2.6.3)。我有一个包含购物清单的MongoDB集合。购物清单的格式为
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"} ] }
现在我想使用 DBCollection
的 update()
方法将新项添加到列表中。但无论我尝试什么它都行不通,虽然它告诉我
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
是 BasicDBObject
,其中包含新项目的数据。我还试图用 BasicDBObjectBuilder
和 JSON.parse()创建
但它没有任何区别。 update()
参数
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.
我也看过其他帖子,试过googleing,但无济于事。我做错了什么?
I also had a look at other posts, tried googleing, but to no avail. What am I doing wrong?
感谢您的帮助!
Oliver
Thanks for any help!
Oliver
推荐答案
是的,上面的代码完全正常。我现在知道我的错误在哪里。我想做防弹,所以我认为最好在DBCollection末端使用save()并明确保存购物清单DBObject:
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 :)
所以一个重要的规则:当您更新 DBCollection
时 - 这是直接发送到数据库! - 不要保存在更新之前查询的 DBObject
!它会覆盖您的更新!
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!
这篇关于使用Java驱动程序更新MongoDB中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!