gpt4 book ai didi

MongoDB + Laravel + jenssegers/laravel-mongodb + 更新嵌套子元素

转载 作者:行者123 更新时间:2023-12-03 15:59:40 25 4
gpt4 key购买 nike

大家好,我是 MongoDB 新手,正在寻找答案

  1. 有什么方法可以更新嵌套数组而不循环它。

    foreach ($post->comments as $key => $comment) {
    if ($comment['posted_by'] == $authUser['id']) {
    $data = $post->update([
    "comments.$key.description" => $dataArray['description'],
    "comments.$key.updated_at" => $dataArray['updated_at'],
    ]);
    }}

我想做如下的事情。

$post = Post::where('_id', $id)->where('comments.*.id', $commentId)->update(array('description' => $desc));

或者我必须为此编写原始 MongoDB 查询。我在主注释下也有 1 级嵌套注释,因此如果我想更新嵌套注释,我必须循环注释数组而不是嵌套注释数组。

if ($subCommentId) {
foreach ($comment as $nestedkey => $nestedComments) {
if ($nestedComments['id'] === $subCommentId && $nestedComments['posted_by'] == $authUser['id']) {
$data = $post->update([
"comments.$key.$nestedkey.description" => $dataArray['description'],
"comments.$key.$nestedkey.updated_at" => $dataArray['updated_at'],
]);
}
}
}

类似这样的事情:

$post = Post::where('_id', $id)->where('comments.*.id', $commentId)->where('comments.*.*.id', $subCommentId)->update(array('description' => $desc));
  • 将评论存储在与数组相同的集合中是否合适,或者我应该为此创建一个新集合,因为最大 BSON 文档大小为 16 MB,并且它可以存储多少评论(例如 10K 或更多)?
  • 下面是我在一个集合下的示例评论数组格式。

    "comments" : [
    {
    "description" : "description some",
    "channel" : "swachhata-citizen-android",
    "user_role" : "Citizen",
    "id" : "5b4dc367d282f",
    "user_role_id" : ObjectId("5accd7f8309a203be03b6441"),
    "created_at" : "2018-07-17 15:52:31",
    "updated_at" : "2018-07-17 15:52:31",
    "ip_address" : "127.0.0.1",
    "user_agent" : "PostmanRuntime/6.4.1",
    "deleted" : false,
    "channel_id" : "5acccfe4309a2038347a5c47",
    "posted_by" : NumberInt(1),
    "comments" : [
    {
    "description" : "some description nested",
    "channel" : "swachhata-citizen-android",
    "user_role" : "Citizen",
    "id" : "5b4dcfc7022db",
    "user_role_id" : ObjectId("5accd7f8309a203be03b6441"),
    "created_at" : "2018-07-17 16:45:19",
    "updated_at" : "2018-07-17 16:45:19",
    "ip_address" : "127.0.0.1",
    "user_agent" : "PostmanRuntime/6.4.1",
    "deleted" : false,
    "channel_id" : "5acccfe4309a2038347a5c47",
    "posted_by" : NumberInt(1)
    }
    ]
    }
    ]

    谢谢。 :)

    最佳答案

    要更新嵌套文档,您应该使用 arrayFilters:

    Post::raw()->updateMany(
    [],
    [ '$set' => ["comments.$[i].comments.$[j].description" => $desc] ],
    [ '$arrayFilters' => [
    [
    [ "i.id" => "5b4dc367d282f" ],
    [ "j.id" => "5b4dcfc7022db" ]
    ]
    ]
    ]
    )

    希望有帮助:)

    关于MongoDB + Laravel + jenssegers/laravel-mongodb + 更新嵌套子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51393785/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com