3

如何推送到以下结构中的嵌套数组?

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

我试过使用

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

wherecoll是集合对象,并且entry是上面的条目。

但该值永远不会被推送,也不会显示错误。我究竟做错了什么?

4

1 回答 1

3

您可以使用点符号引用子文档“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" ] } }
}
于 2013-05-28T15:45:19.237 回答