2014-04-19 86 views
0

看了幾本書後,mongo db參考和其他stackoverflow問題,我似乎無法得到這個查詢正確。如何實現MongoDB查詢來查找數組內所有對象的鍵?

我有以下數據結構:

帖子集合:

{ 
    "content" : "...", 
    "comments" : [ 
     { 
      "author" : "joe", 
      "score" : 3, 
      "comment" : "nice post" 
     }, 
     { 
      "author" : "bob", 
      "score" : 5, 
      "comment" : "nice" 
     }] 
} 

我試圖讓所有的筆者的是內部各自爲陣內的對象名一個把手幫手,不在控制檯中。所以,我有這樣的事情:

... 
commentsAuthors: function() { 
    return Collection.find({...}); 
} 

更新: 我決定把我的陣列減少到只有一個字符串數組,這是我後來查詢是這樣的:

新陣列:

{ 
    "content" : "...", 
    "comments" : ["value1", "value2", "..."] 
} 

MeteorJS把手幫手:

Template.courseEdit.helpers({ 
comments: function(){ 
    var cursor = Courses.find({"_id": "8mBATtGyyWsGr2PwW"}, {"comments": 1, "_id": 0}).fetch(); 

return cursor.map(function(doc, index, cursor){ 
    var comment = doc.comments; 
    console.log(comment); 
    return comment; 
    }); 
} 
}); 

在這一點上,我能夠呈現整個陣列在我看來,這個{{#each}}...{{/each}}

<ul class="list-unstyled"> 
    {{#each comments}} 
    <li class="pl-14"><i class="icon-checkmark"></i> {{this}}</li> 
    {{/each}} 
</ul> 

但是我得到了整個陣列在一個單一的列表項。

如何爲每個數組字符串創建單獨的列表項?

在此先感謝。

回答

0

您可以通過限制領域

db.collection.find({"content" : "..."},{"comments.author":1}) 
+0

感謝您的幫助,但我試圖具體獲取所有的鍵值'comments'數組內的對象。任何想法如何?注意:在Handlebars助手中,不在控制檯中。 – Gus

2

只得到某些領域應該是那麼容易,因爲(與你的集合名稱替換posts):

db.posts.distinct("comments.author") 

或者,如果你需要它的每一篇:

db.posts.aggregate([ 
    { $unwind: "$comments" }, 
    { $group: { "_id": "$_id", authors: { "$addToSet": "$comments.author"} } } 
]) 
+0

感謝您的幫助,但是我試圖具體獲取評論數組內的對象的鍵的所有值。任何想法如何?注意:在Handlebars助手中,不在控制檯中。 – Gus

相關問題