如何使用 Mongoose 查找数组元素?

How to find array elements with Mongoose?

我在 Mongoose 模型中有一个数组作为子文档,定义如下:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var schema = Schema({
    author: { type: Schema.Types.ObjectId, ref: 'Author' },
    pages: [{
        number: Number, 
        type: { type: String, enum: ['boring', 'fun']},
    }]
});

module.exports = mongoose.model('Book', schema);

现在我想获得某个作者所有书籍的总页数 'fun'。我发现许多类似的问题(和答案)讨论了如何在这种情况下找到带有有趣页面的 Books,但是我想获得所有有趣页面的数组,或者至少是该数组的长度,但如果可能的话我想得到数组本身。我该怎么做?

谢谢,

我相信,除了语法之外,这是不言自明的:

Book.aggregate(

    { 
        $match: {
            author: ObjectId("12-bytes-of-hex")
        }
     },

    { $unwind: "$pages" },

    { $group: {
        _id: "$pages.type",
        count: { $sum: 1 }
    }}
)