【发布时间】:2011-07-23 19:23:43
【问题描述】:
我正在使用带有官方 Java 驱动程序(版本 2.6.3)的 MongoDB。我有一个包含购物清单的 MongoDB 集合。购物清单的格式为
{ "_id" : { "$oid" : "4e2af1f43f8de96494d5271d"} ,
"name" : "default" ,
"items" : [ { "description" : "Cheese" , "quantity" : 1 , "unit" : "kg"} ,
{ "description" : "Water" , "quantity" : 3 , "unit" : "bottle"} ] }
现在我想用update()方法DBCollection向列表中添加一个新项目。但是无论我尝试什么都行不通,尽管它告诉我
{ "updatedExisting" : true , "n" : 1 , "connectionId" : 63 , "err" : null , "ok" : 1.0}
我的代码执行以下操作:
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() 参数,但没有区别。
我还看了其他帖子,尝试了谷歌搜索,但无济于事。我做错了什么?
感谢您的帮助!
奥利弗
【问题讨论】:
-
我用 MongoDB 2.5.3 驱动程序运行了那个确切的代码,它运行良好。确保您正在寻找正确的数据库。
-
这对我很有用,可以更好地理解 Mongo 的 Java 驱动程序中有些晦涩的语法。谢谢!