通过Java向Mongo Collection中的每个文档添加新字段

时间:2019-07-03 05:24:57

标签: java json spring mongodb mongo-java-driver

如何为现有集合中的每个文档添加新字段?

这是我到目前为止尝试过的

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);

1 个答案:

答案 0 :(得分:1)

您应该使用多重更新:

    DBObject queryAll = new BasicDBObject();
    DBObject newValue = new BasicDBObject("xxx", "newField");
    DBObject update = new BasicDBObject("$set", newValue);
    collection.updateMulti(queryAll, update);