Search code examples
javajsonspringmongodbmongo-java-driver

Add new field to every document in Mongo Collection through Java


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

Solution

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