【问题标题】:Count elements in an array from a document从文档中计算数组中的元素
【发布时间】:2023-04-05 03:56:01
【问题描述】:

我正在尝试建立一个博客,其中每篇文章都包含多个段落。我只想计算特定帖子中的段落数。在“博客”集合中,我的文档(=帖子)如下:

{ id : String
  title : String
  paragraphs : [ { position: Int, body: String } ] }

我想要一个返回整数的函数。也许接近:

var NumberParagraphs = Blog.find( {id: id} ).paragraphs.length 

(显然这不起作用!)...你能告诉我用哪种方法进行调查吗?在网上搜索时,我对.count()$size.aggregate 的用例感到困惑

【问题讨论】:

    标签: javascript mongodb meteor count


    【解决方案1】:

    .find() 方法不返回单个文档。所以你要么想把这些文档循环成一个数组:

    Blog.find({ id: id }).fetch().forEach(function(doc) {
         var NumParagraphs = doc.paragraphs.length;
         // Then do something useful
    })
    

    或者只是.findOne() 用于单个文档:

    var doc = Blog.findOne({ id: id });
    var NumParagraphs = doc.paragraphs.length;
    

    相同的原则适用于 MongoDB 的原始方法,而不仅仅是流星。

    【讨论】:

      【解决方案2】:

      如果您想知道的话,还有一个使用聚合方法和 $size 的示例:

      var numParagraphs = Blog.aggregate([
          {
              $match : {
                  "_id" : id
              }
          },
          {
              $project : {
                  "pCount" : {$size : '$paragraphs'}
              }
          }
      ]).pCount;
      

      【讨论】:

        【解决方案3】:

        你应该这样做

        Blog.findOne({_id:id}).paragraphs.length
        

        谢谢

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-02-17
          • 2016-07-09
          • 1970-01-01
          • 1970-01-01
          • 2016-05-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多