Skizit
Skizit

Reputation: 44852

MongoDB Java - Pushing to a nested Array?

How do I push to a nested array in the following structure?

{
    level1 : {
       - arr1: [
                  "val1"
               ]
    }
}

I've tried using

 coll.update(entry, new BasicDBObject("$push", new BasicDBObject("level1", new BasicDBObject("arr1", "val2"))));

where coll is the collection object and entry is the entry above.

but the value is never pushed and no error is shown. What am I doing wrong?

Upvotes: 3

Views: 2548

Answers (1)

Trisha
Trisha

Reputation: 3931

You can reference the array in the sub-document "level1" using dot notation. So, instead of creating nested DBObjects like you've done, you simply need:

coll.update(entry, new BasicDBObject("$push", new BasicDBObject("level1.arr1", "val2")));

I wrote a test to show this works:

@Test
public void shouldPushANewValueOntoANesstedArray() throws UnknownHostException {
    final MongoClient mongoClient = new MongoClient();
    final DBCollection coll = mongoClient.getDB("TheDatabase").getCollection("TheCollection");
    coll.drop();

    //Inserting the array into the database
    final BasicDBList array = new BasicDBList();
    array.add("val1");

    final BasicDBObject entry = new BasicDBObject("level1", new BasicDBObject("arr1", array));
    coll.insert(entry);

    // results in:
    // { "_id" : ObjectId("51a4cfdd3004a84dde78d79c"), "level1" : { "arr1" : [ "val1" ] } }

    //do the update
    coll.update(entry, new BasicDBObject("$push", new BasicDBObject("level1.arr1", "val2")));
    // results in:
    // { "_id" : ObjectId("51a4cfdd3004a84dde78d79c"), "level1" : { "arr1" : [ "val1", "val2" ] } }
}

Upvotes: 3

Related Questions