如何在MongoDB上将数据更新为多层结构

时间:2014-01-09 08:12:59

标签: mongodb

我想在其父母的评论中嵌入一个新的评论文件。

以下是MongoDB上的博客文章。

{ '_id': 1,
  'title': xxx,
  'content': xxx,
  'comments': [
          {
                'id': 1,
                'author': xxx,
                'content':xxx
          },
          {
                'id': 2,
                'author': xxx,
                'content':xxx
          }
  ]
}

我想添加一条新评论,即其父母的评论ID为1。

我该怎么办?

'comments': [
          {
                'id': 1,
                'author': xxx,
                'content':xxx
                'comments':[
                        {
                              'id':3,
                              'author': xxx,
                              'content':xxx
                        }
                ]
          },
          {
                'id': 2,
                'author': xxx,
                'content':xxx
          }
  ]

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以按照以下方式执行此操作:

db.collection.update({"_id" : 1, "comments.id" : 1},{$push : {"comments.$.comments" : {id : 3, author : "xxx", content:"xxx"}}})