我需要将一个数组元素推入mongoDb文档中的内部元素

问题描述 投票:1回答:2

我的意图是将一个数组推入到嵌入内部的索引'jnl_articles'中。如何使用原始mongodb查询实现它。我正在使用带有laravel框架的Jessengers mongoDB。

这是文件:

{
"_id" : ObjectId("5ca70c3c5586e920ba79df59"),
"jnl_volumes" : [
     {
        "volume_name" : 6,
        "jnl_issues" : [ 
            {
                "issue_name" : "1",
                "created_date" : "2019-04-10",
                "jnl_articles" : [],
                "issue_status" : "1"
            }, 
        ]
    }
]

}

下面是我需要推送的数组项:

[
{
    "article_name": "art1",
    "created_date": "2019-04-10",
    "article_order": 1
},
{
    "article_name": "art2",
    "created_date": "2019-04-10",
    "article_order": 2
}

]

我需要获得的期望结果如下。

  {
    "_id" : ObjectId("5ca70c3c5586e920ba79df59"),
    "jnl_volumes" : [
     {
        "volume_name" : 6,
        "jnl_issues" : [ 
            {
                "issue_name" : "1",
                "created_date" : "2019-04-10",
                "jnl_articles" : [ 
                    {
                        "article_name" : "art1",
                        "created_date" : "2019-04-10",
                        "article_order" : 1
                    }, 
                    {
                        "article_name" : "art2",
                        "created_date" : "2019-04-10",
                        "article_order" : 2
                    }
                ],
                "issue_status" : "1"
            }, 
        ]
    }
]

}

mongodb mongodb-query
2个回答
1
投票

假设您想将文章推送到第一卷的第一期,它看起来像:

{ $push: { "jnl_volumes.0.jnl_issues.0.jnl_articles": { $each: [] } } }
// use first volume ----^            ^                  ^      ^
// use first issue ------------------/                  |      |
// use $each to append an array of elements ------------/      |
// your array of articles -------------------------------------/

$push$each的文档。


1
投票

试试这个:

await table_name.update({
    _id: ObjectId("5ca70c3c5586e920ba79df59")
}, {
    $push: {
        jnl_articles: $each: [{
            object
        }, {
            object
        }]
    }
});

要么

for (const object of array) {
    await table_name.update(
    {_id: ObjectId("5ca70c3c5586e920ba79df59")},
    {$push: { jnl_articles: object } });
}
© www.soinside.com 2019 - 2024. All rights reserved.