2

有没有办法通过 id 或其他字段更新嵌套文档?

我使用“单个文档中的完整树”并且事先不知道嵌套可以有多深。需要更新,例如,回答 {id:'104'}。我可以通过“点表示法”做到这一点,但由于我不知道嵌套的级别(深度),我无法预测我'comment.answers.answers....answers.'能走多长时间。

有什么方法可以直接查找和更新 id:'104',还是我还需要通过某种深度标记?

{
 title:'some title',
 comment:
     {
        id:'101'
        author:'Joe',
        text:'some comment',
        answers:
        [
            {
              id:'102'
              author:'Joe',
              text:'first answer to comment',
              answers:
                    [
                       {
                           id:'103'
                           author:'Done',
                           text:'first answer to first answer to comment',
                           answers:[]
                       },
                       {
                           id:'104'
                           author:'Bob',
                           text:'Second answer to first answer to comment',
                           answers:[]
                       }

                    ]

            },

            {
            },

            {
            },
        ]
     }
}

我使用Node.JS MongoDB 驱动程序

4

2 回答 2

1

我认为您应该存储每个节点的深度级别,然后动态创建查询。

于 2012-07-02T04:41:35.897 回答
1

简而言之,没有真正好的方法来进行这种查询。有几个选项:

您可以使用长语句创建查询,$or为文档指定每个可能的嵌套位置:

{ comment.id: 103, $or [
                        { comment.answers.id: 103 }, 
                        { comment.answers.answers.id: 103 },
                        { comment.answers.answers.answers.id: 103 } 
                       ] 
}

有关$or 运算符的更多信息,请参阅文档

事实上,更好和更可持续的解决方案是使用不同的模式,其中所有评论和答案都存储在一个平面数组中,然后存储有关comments.parent字段中评论之间关系的信息。例如:

 { comment: [
           { id: 1 }
           { id: 2, parent: 1 }
          ] }

有关其他选项和对可能的注释层次建模方法的更深入讨论,请查看 MongoDB 文档中的存储注释用例

MongoDB 中的 Trees 中还有许多您可能需要考虑的策略。

于 2012-07-02T15:01:00.350 回答