简体   繁体   English

计算文档中数组中的元素

[英]Count elements in an array from a document

I am trying to set up a blog, where each post contains multiple paragraphs. 我正在尝试建立一个博客,其中每个帖子包含多个段落。 I would simply like to count the number of paragraphs in a particular post. 我只想计算一个特定帖子中的段落数。 In the "Blog" collection, my documents (=posts) are as follow : 在“博客”集合中,我的文档(=帖子)如下:

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

I would like a function returning an Integer. 我想要一个返回整数的函数。 Maybe something close to : 也许接近:

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

(obviously this doesn't work ! ) ... Could you advise me which way to investigate? (显然这是行不通的!)...您能建议我进行哪种调查吗? while searching the net, I am getting confused between use case for .count() , $size , or .aggregate 在网上搜索时,我对.count()$size.aggregate用例感到困惑

The .find() method does not return a single document. .find()方法不返回单个文档。 So you either want to loop those documents as an array: 因此,您要么要将这些文档作为数组循环:

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

Or just .findOne() for a single document: 或者只是.findOne()用于单个文档:

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

The same principles apply to the raw methods for MongoDB, not just meteor. 同样的原则适用于MongoDB的原始方法,而不仅仅是流星。

And an example using the aggregate method and $size, in case you were wondering: 还有一个使用聚合方法和$ size的示例,以防万一您想知道:

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

You should do 你应该做

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

Thanks 谢谢

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

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