繁体   English   中英

如何实现Mongo DB查询以查找数组内所有对象的键?

[英]How do I implement Mongo DB query to find key in all objects inside an array?

在查看了几本书,mongo db参考和其他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 Handlebars帮手:

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>

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

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

提前致谢。

应该像使用您的集合名称替换posts一样简单:

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

或者,如果您需要每个帖子:

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

您只能通过限制字段来获取某些字段

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM