0

在查看了几本书、mongo db reference 和其他 stackoverflow 问题之后,我似乎无法正确地得到这个查询。

我有以下数据结构:

帖子集合:

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

我想要得到的是Handlebars helper中数组的每个对象中的所有作者姓名,而不是在控制台中。所以我会有类似的东西:

...
 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>

但是,我将整个数组放在一个列表项中。

如何为每个数组字符串创建单独的列表项?

提前致谢。

4

2 回答 2

2

应该像(替换posts为您的集合名称)一样简单:

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

或者,如果您在每个帖子中都需要它:

db.posts.aggregate([
  { $unwind: "$comments" }, 
  { $group: { "_id": "$_id", authors: { "$addToSet": "$comments.author"} } } 
])
于 2014-04-19T06:39:40.220 回答
0

限制字段​​只能获取特定字段

 db.collection.find({"content" : "..."},{"comments.author":1})
于 2014-04-19T06:10:57.283 回答