用猫鼬计数数组中的字段

时间:2018-10-16 17:29:03

标签: arrays mongoose count field

我想对数组求和。这个模型

modelDetail.aggregate([
            {
                $group: {
                    _id: '$main_section.first_name',  
                    count: {$sum: 'first_array.second_array.field_name'}
                }
            }
        ], function (err, result) {
                if (err) {
                    //next(err);
                    console.log(err);
                } else {
                    console.log(JSON.stringify(result));
                    res.json(result);
                }
        });

这将为所有结果带来0。输出低于

[{"_id":"first","count":0},
{"_id":"second","count":0},
{"_id":"third","count":0},
{"_id":"Fourth","count":0},
{"_id":"Fifth","count":0},// i expected 8 here
{"_id":"Sixth","count":0},
{"_id":"Seventh","count":0},// i expected 5 here
{"_id":"Eigth","count":0},// i expected 3 here
{"_id":"Ninth","count":0}]

我想获得所有数据的计数,这就是我的模式

var userSchema = mongoose.Schema({
    main_section        :{
        first_name          : String
    },

    first_Array :[{//1st level
        array_info          : String,
        second_array            :[{//2nd level
            detail1             : String,//3rd level
            field_name          : String
        }]
    }]
});

任何帮助将不胜感激

0 个答案:

没有答案