The following code haven't worked for me:
public void addFieldWithValueToDoc(String DBName, String collName, String docID, String key, String value) {
    BasicDBObject setNewFieldQuery = new BasicDBObject().append("$set", new BasicDBObject().append(key, value));
    mongoClient.getDB(DBName).getCollection(collName).update(new BasicDBObject().append("_id", docID), setNewFieldQuery);
}
Where mongoClient variable's type is MongoClient.
It's inspired by Add new field to a collection in MongoDB . What's wrong and how to do it right? Thanks.
I've written a JUnit test to prove that your code does work:
@Test
public void shouldUpdateAnExistingDocumentWithANewKeyAndValue() {
    // Given
    String docID = "someId";
    collection.save(new BasicDBObject("_id", docID));
    assertThat(collection.find().count(), is(1));
    // When
    String key = "newKeyName";
    String value = "newKeyValue";
    addFieldWithValueToDoc(db.getName(), collection.getName(), docID, key, value);
    // Then
    assertThat(collection.findOne().get(key).toString(), is(value));
}
public void addFieldWithValueToDoc(String DBName, String collName, String docID, String key, String value) {
    BasicDBObject setNewFieldQuery = new BasicDBObject().append("$set", new BasicDBObject().append(key, value));
    mongoClient.getDB(DBName).getCollection(collName).update(new BasicDBObject().append("_id", docID), setNewFieldQuery);
}
So your code is correct, although I'd like to point out some comments on style that would make it more readable:
DBName should be dbName, new BasicDBObject().append(key, value) use new BasicDBObject(key, value)This code does the same thing as your code, but is shorter and simpler:
public void addFieldWithValueToDoc(String dbName, String collName, String docID, String key, String value) {
    mongoClient.getDB(dbName).getCollection(collName).update(new BasicDBObject("_id", docID),
                                                             new BasicDBObject("$set", new BasicDBObject(key, value)));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With