Bertrand Engogram
Bertrand Engogram

Reputation: 629

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

Upvotes: 2

Views: 455

Answers (3)

khem poudel
khem poudel

Reputation: 587

You should do

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

Thanks

Upvotes: 0

natedog
natedog

Reputation: 141

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;

Upvotes: 1

Blakes Seven
Blakes Seven

Reputation: 50406

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.

Upvotes: 2

Related Questions