通过 Java 向 Mongo 集合中的每个文档添加新字段
Add new field to every document in Mongo Collection through Java
如何向现有集合中的每个文档添加新字段?
这是我目前尝试过的方法
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);
你应该使用多更新:
DBObject queryAll = new BasicDBObject();
DBObject newValue = new BasicDBObject("xxx", "newField");
DBObject update = new BasicDBObject("$set", newValue);
collection.updateMulti(queryAll, update);
如何向现有集合中的每个文档添加新字段?
这是我目前尝试过的方法
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);
你应该使用多更新:
DBObject queryAll = new BasicDBObject();
DBObject newValue = new BasicDBObject("xxx", "newField");
DBObject update = new BasicDBObject("$set", newValue);
collection.updateMulti(queryAll, update);