如何为现有集合中的每个文档添加新字段?
这是我到目前为止尝试过的
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("myDB");
DBCollection collection = db.getCollection("myCollection");
DBObject test = new BasicDBObject();
DBObject add = new BasicDBObject();
add.put("xxx", "newField");
collection.update(add, test);
答案 0 :(得分:1)
您应该使用多重更新:
DBObject queryAll = new BasicDBObject();
DBObject newValue = new BasicDBObject("xxx", "newField");
DBObject update = new BasicDBObject("$set", newValue);
collection.updateMulti(queryAll, update);