G.Brown
G.Brown

Reputation: 389

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

Upvotes: 0

Views: 500

Answers (1)

HPCS
HPCS

Reputation: 1454

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

Upvotes: 1

Related Questions