简体   繁体   English

使用Java驱动程序更新MongoDB中的数组

[英]Updating an array in MongoDB using Java driver

I'm using MongoDB with the official Java driver (version 2.6.3). 我正在使用MongoDB和官方Java驱动程序(版本2.6.3)。 I have a MongoDB collection that contains shopping lists. 我有一个包含购物清单的MongoDB集合。 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 . 现在我想使用DBCollectionupdate()方法将新项添加到列表中。 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. newShoppingItem是一个BasicDBObject ,它包含新项的数据。 I also tried to create the update() parameters with BasicDBObjectBuilder and JSON.parse() but it makes no difference. 我还尝试使用BasicDBObjectBuilderJSON.parse()创建update()参数,但它没有任何区别。

I also had a look at other posts, tried googleing, but to no avail. 我也看过其他帖子,试过googleing,但无济于事。 What am I doing wrong? 我究竟做错了什么?

Thanks for any help! 谢谢你的帮助!
Oliver 奥利弗

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: 我想做防弹,所以我认为最好在DBCollection末端使用save()并明确保存购物清单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! 所以一条重要的规则是:更新DBCollection - 这会直接发送到数据库! – don't save a DBObject that you queried before the update! - 不要保存在更新之前查询的DBObject It will overwrite your update! 它会覆盖您的更新!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM