您可以使用点符号引用子文档“level1”中的数组。因此,您无需像之前那样创建嵌套 DBObject,只需:
coll.update(entry, new BasicDBObject("$push", new BasicDBObject("level1.arr1", "val2")));
我写了一个测试来证明这个工作:
@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" ] } }
}