Anda dapat mereferensikan array di sub-dokumen "level1" menggunakan notasi titik. Jadi, alih-alih membuat objek DBO bersarang seperti yang telah Anda lakukan, Anda hanya perlu:
coll.update(entry, new BasicDBObject("$push", new BasicDBObject("level1.arr1", "val2")));
Saya menulis tes untuk menunjukkan ini berfungsi:
@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" ] } }
}