【问题标题】:Update recursive document in MongoDB更新 MongoDB 中的递归文档
【发布时间】:2021-07-18 04:44:26
【问题描述】:

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

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

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

  • 要回复的对象保证存在。
  • 要发布回复的对象的路径是已知的(即,我们有一系列 _id 属性可供导航)。
  • 递归深度没有限制。

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

基于后者,我的尝试是:

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

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

更新:以下示例。下面是一个来自 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


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

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-10
      • 1970-01-01
      • 2011-08-04
      • 1970-01-01
      相关资源
      最近更新 更多