MongoDB Java - 推送到嵌套数组?

问题描述:

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

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

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

我试过使用

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

其中 coll 是集合对象,entry 是上面的条目.

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?

您可以使用点表示法引用子文档level1"中的数组.因此,无需像您那样创建嵌套的 DBObject,您只需要:

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" ] } }
}