首页 > 解决方案 > 更新 MongoDB 中的递归文档

问题描述

我的一个 MongoDB 集合中有一个递归结构,如下所示:

{
    "id": String,
    "date": Date,
    "text": String
    "replies": [{
        // Same structure as above
    }]
}

我需要通过添加对嵌套文档的回复来更新此层次结构中的文档。保证如下:

搜索 SO 给我以下相关问题:

基于后者,我的尝试是:

await commCollection.update(
    { _id: topLevel['_id'] },
    {
        $push: {
            'replies.$[].$[comment_arr].replies': {
                id: commentId,
                text: comment,
                date,
                replies: []
            }
        }
    },
    { arrayFilters: [{ 'comment_arr.id': responseTo }]}
);

其中topLevel是根文档,responseToid要添加回复的对象的属性。然而,这似乎不起作用。我做错了什么,我该如何做到这一点?

更新:下面的一个例子。这是来自 MongoDB Atlas 的文档示例:

{
    "_id": {
        "$oid": "605fdb8d933c5f50b4d2225e"
    },
    "id": "mr9pwc",
    "username": "recrimination-logistical",
    "upvotes": {
        "$numberInt": "0"
    },
    "downvotes": {
        "$numberInt": "0"
    },
    "text": "Top-level comment",
    "date": {
        "$date": {
            "$numberLong": "1616894861300"
        }
    },
    "replies": [{
        "id": "dflu1h",
        "username": "patrolman-hurt",
        "upvotes": {
            "$numberInt": "0"
        },
        "downvotes": {
            "$numberInt": "0"
        },
        "text": "Testing reply level 1!",
        "date": {
            "$date": {
                "$numberLong": "1618387567042"
            }
        },
        "replies": []    // ----> want to add a reply here
    }]
}

我已经指出我们希望在哪里添加回复。responseTo在这种情况下是dflu1h.

标签: mongodb

解决方案


  • 只需要删除$[]位置
  • arrayFilters 中的字段名称必须是以小写字母开头的字母数字字符串,comment_arr仅更改为任何字母,例如commentArr,删除特殊字符
await commCollection.update(
  { _id: topLevel['_id'] },
  {
    $push: {
      "replies.$[commentArr].replies": {
        id: commentId,
        text: comment,
        date,
        replies: []
      }
    }
  },
  { arrayFilters: [{ "commentArr.id": responseTo }] }
)

操场


推荐阅读