Paw Dethlefsen
Paw Dethlefsen

Reputation: 13

Mongoose sum aggregation

I have this mongoose schema where i would like get the sum of sizes based on the creator.

creator: { type: Schema.Types.ObjectId, ref: 'User' },
archives: [{
    archiveId: String, 
    url: String,
    name: String,
    size: Number,
    isSet: { type: Boolean, default: false },
    timestamp: { type: Date, default: Date.now() }
}]

this is what i have tried so far, but the total keeps coming up as 0

var ObjectId = require('mongoose').Types.ObjectId;
    ArchiveModel.aggregate(
        {
            $match: {
                'creator': new ObjectId(creatorId),
            }
        },
        {
            $group: {
                _id: null,
                total: {$sum: '$archives.size'}
            }
        },
        {

            $project: {
                creator: 1,
                total: 1

            }

        }, function(err, result) {

            console.log(err);
            console.log(result);
        }

    );

Upvotes: 1

Views: 828

Answers (1)

jtmarmon
jtmarmon

Reputation: 6169

db.col.aggregate([
    // Match all docs with the right creator
    {$match: {creator: my_creator}}, 
    // Array of arrays into a single array
    {$unwind: '$archives'},
    // Get the count of all docs
    {$group: {_id: 'total', count: {$sum: 1}}}
]);

Upvotes: 1

Related Questions