我有一个包含List作为字段之一的类。如何更新此字段。
找到更新字段的示例
BasicDBObject newDocument3 = new BasicDBObject().append("$set", new
BasicDBObject().append("type", "dedicated server"));
collection.update(new BasicDBObject().append("hosting", "hostA"), newDocument3);
来自链接 - > http://www.mkyong.com/mongodb/java-mongodb-update-document/
所以这就是我试过的
BasicDBObject objectUpdateCommand = new BasicDBObject("$push", new
BasicDBObject("someList", stringValue));
collection.update(new BasicDBObject().append("id", user.getId()).append("email",
user.getEmail()), objectUpdateCommand);
结果:没有变化。
我错过了什么?
尝试shell并且它有效[我知道它不匹配所有ID但它适用于测试目的]
db.user.update( { Id: 'yourid'}, {$push: { someList: 'appendNewValue'} } )
答案 0 :(得分:2)
我已将以下行插入集合中。
{ "_id" : ObjectId("50bc89ef88555f5ad35da8ba"), "id" : 1, "email" : "test1@test.com", "list" : [ "list1", "list2" ] }
{ "_id" : ObjectId("50bc89f788555f5ad35da8bb"), "id" : 2, "email" : "test2@test.com", "list" : [ "list1", "list2" ] }
然后通过使用以下代码,我能够更新id = 1的文档。
BasicDBObject cmd = new BasicDBObject().append("$push", new BasicDBObject("list", "list3"));
coll.update(new BasicDBObject().append("id", 1).append("email","test1@test.com"), cmd);
更新后的行如下所示:
{ "_id" : ObjectId("50bc89ef88555f5ad35da8ba"), "id" : 2, "email" : "test2@test.com", "list" : [ "list1", "list2" ] }
{ "_id" : ObjectId("50bc89f788555f5ad35da8bb"), "email" : "test1@test.com", "id" : 1, "list" : [ "list1", "list2", "list3" ] }
再次检查您的代码。它应该与此代码一起使用。