How can I add a new field to every document in an existent collection?
This is what I have tried so far
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);
You should use update multi:
DBObject queryAll = new BasicDBObject();
DBObject newValue = new BasicDBObject("xxx", "newField");
DBObject update = new BasicDBObject("$set", newValue);
collection.updateMulti(queryAll, update);