CAM
CAM

Reputation: 185

MongoDB Aggregating Array Items

Given the Schema Displayed Below & MongoDB shell version: 2.0.4:

How would I go about counting the number of items in the impressions array ?

I am thinking I have to do a Map Reduce, which seems to be a little complex, I thought that the count Function would do it.
Can someone Demonstrate this?

Mongo Schema

Upvotes: 1

Views: 418

Answers (1)

Stennie
Stennie

Reputation: 65393

A simple example of counting is:

var count = 0;
db.engagement.find({company_name: "me"},{impressions:1}).forEach(
    function (doc) {
        count += doc.impressions.length;
    }
)
print("Impressions: " + count);

If you have a large number of documents to process, you would be better maintaining the count as an explicit field. You could either update the count when pushing to the impressions array, or use an incremental MapReduce to re-count for updated documents as needed.

Upvotes: 1

Related Questions