Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add field with value to existing document in MongoDB via Java API

Tags:

java

mongodb

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.

like image 795
rok Avatar asked Oct 28 '25 01:10

rok


1 Answers

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:

  1. Parameters and variables should start with a lower-case letter. DBName should be dbName,
  2. You don't need 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)));
}
like image 60
Trisha Avatar answered Oct 30 '25 17:10

Trisha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!