MongoDB Java - 推送到嵌套数组? [英] MongoDB Java - Pushing to a nested Array?

查看:32
本文介绍了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" ] } }
}

这篇关于MongoDB Java - 推送到嵌套数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆