jeff
jeff

Reputation: 13643

How to find array elements with Mongoose?

I have an array as a subdocument in the Mongoose model defined as follows:

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);

Now I want to get the total number of 'fun' pages across all books by a certain author. Many similar questions (and answers) I found discuss how to find Books with fun pages in this scenario, however I want to get an array of all fun pages, or at least the length of that array, but if possible I would like to get the array itself. How can I do this?

Thanks,

Upvotes: 0

Views: 156

Answers (1)

nadavvadan
nadavvadan

Reputation: 4190

I believe that, aside from syntax, this is pretty self-explanatory:

Book.aggregate(

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

    { $unwind: "$pages" },

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

Upvotes: 1

Related Questions