Calculating collection stats for a subset of documents in MongoDB
This may not be the most efficient or accurate way to do it, but I ended up using a Mongoose plugin to get the size of the JSON representation of the document before it's saved:
module.exports = exports = function defaultPlugin(schema, options){ schema.add({ userId: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true }, recordSize: Number }); schema.pre('save', function(next) { this.recordSize = JSON.stringify(this).length; next(); });}
This will convert the schema object to a JSON representation, get it's length, then store the size in the document itself. I understand that this will actually add a tiny bit of extra storage to record the size, but it's the best I could come up with.
Then, to generate a storage report, I'm using a simple aggregate
call to get the sum of all of the recordSize
values in the collection, filtered by userId:
mongoose.model('YouCollectionName').aggregate([{ $match: { userId: userId }},{ $group: { _id: null, recordSize: { $sum: '$recordSize'}, recordCount: { $sum: 1 } }}], function (err, results) { //Do something with your results});