简体   繁体   中英

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

The .find() method does not return a single document. 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:

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

The same principles apply to the raw methods for MongoDB, not just meteor.

And an example using the aggregate method and $size, in case you were wondering:

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

You should do

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

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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