【问题标题】:Mongoose sum aggregation猫鼬总和聚合
【发布时间】:2015-05-19 06:03:57
【问题描述】:

我有这个猫鼬模式,我想根据创建者获取大小的总和。

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() }
}]

这是我迄今为止尝试过的,但总数一直为 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);
        }

    );

【问题讨论】:

    标签: mongoose


    【解决方案1】:
    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}}}
    ]);
    

    【讨论】:

      猜你喜欢
      • 2019-08-29
      • 1970-01-01
      • 1970-01-01
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 2015-03-04
      • 2016-02-02
      • 2015-09-15
      相关资源
      最近更新 更多