MongoDB Java - 推送到嵌套数组?

时间:2013-05-24 00:48:49

标签: java mongodb

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

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

我尝试过使用

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

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

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

1 个答案:

答案 0 :(得分: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" ] } }
}