【问题标题】:How do I implement Mongo DB query to find key in all objects inside an array?如何实现 Mongo DB 查询以查找数组内所有对象的键?
【发布时间】:2014-06-03 16:41:10
【问题描述】:

在查阅了几本书、mongo db reference 和其他 stackoverflow 问题后,我似乎无法正确查询此查询。

我有以下数据结构:

帖子集合:

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

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

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

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

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

提前致谢。

【问题讨论】:

    标签: mongodb meteor spacebars


    【解决方案1】:

    应该很简单(将posts 替换为您的收藏名称):

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

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

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

    【讨论】:

    • 感谢您的帮助,但是我正在尝试专门获取 cmets 数组中对象的所有键值。有什么想法吗?注意:在 Handlebars 助手中,而不是在控制台中。
    【解决方案2】:

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

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

    【讨论】:

    • 感谢您的帮助,但是我正在尝试专门获取 comments 数组中对象的所有键值。有什么想法吗?注意:在 Handlebars 助手中,而不是在控制台中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 2010-12-13
    • 2021-07-04
    • 1970-01-01
    • 2013-08-24
    相关资源
    最近更新 更多