2014-01-09 73 views
1

我想將新的評論文檔嵌入到其父項的評論中。如何將數據更新到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 
      } 
    ] 

謝謝!

回答

0

如下你可以這樣做:

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

我有一點困惑的「意見$意見。」。 '$'的效果是什麼? –

+0

@ user2742381:'$'是[位置運算符](http://docs.mongodb.org/manual/reference/operator/update/positional/)。它充當查詢中每個文檔的第一個匹配數組元素的佔位符(因此在這種情況下,數組的第一個元素的'comments.id'爲'1')。 – Stennie

+0

@Stennie我明白了。謝謝。 –