更新嵌套树mongoDB,node.js中的后代

有没有办法通过ID或其他字段更新嵌套的文件?

我使用“ 单一文件中的完整树 ”,事先不知道嵌套深度可以达到多less。 需要更新,例如,用{id:'104'}回答。 我可以通过'点符号'来做到这一点,但是因为我不知道嵌套的级别(深度),所以我无法预测我的'comment.answers.answers....answers.'多久'comment.answers.answers....answers.' 可以去。

有什么办法可以直接find并更新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驱动程序

总之,没有什么好方法可以做这样的查询。 有几个选项:

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

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

有关$或操作符的更多信息, 请参阅文档 。

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

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

有关其他选项以及build模注释层次结构的更深入讨论,请查看MongoDB文档中的“ 存储注释用例 ”。

MongoDB中的树也有许多策略,您可能需要考虑。

我认为你应该存储每个节点的深度级别,然后dynamic地创build查询。