3

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?

1
  • 1
    coll.update(entry, new BasicDBObject("$push", new BasicDBObject("level1.arr1", "val2"))) Commented May 24, 2013 at 2:19

1 Answer 1

3

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

Comments

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.