0

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

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

6 Comments

Used your code, but new field is not getting appended to all jsons
is it append to some of the documents? or not at all?
Code seems correct, but it's not at all appending the field to json
Does collection.find() returns any documents?
If I use for loop in this context, everything will be overridden by last value. You think is there a way to update them one by one?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.