0

I have these collections, stats and items. Stats has one item as subdocument:

var ItemSchema = new Schema({ 
    type: String,
    created_at: Date,
    updated_at: {
        type: Date,
        default: Date.now()
    }
});

var StatsSchema = new Schema({ 
    item: {
        type: Schema.ObjectId,
        ref: 'Item'
    },
    url: String,
    date: Date,
    action: String,
    hourly: Number
});

I'd like to aggregate Stats grouping by item.type. Is it possible?

I tried something like this but without luck:

db.stats.aggregate(
    { $project: { _id: 1, hourly: 1, action: 1, item: 1, type: '$item.type' } }, 
    { $group: { _id: { action: '$action', type: '$item.type' }, total: { $sum: '$hourly' } } }
)
michelem
  • 14,430
  • 5
  • 50
  • 66
  • You have a referenced schema with information stored in separate collections. MongoDB does not "join" data across collections with operations like this. If you need this type of action you would be better of "embedding" the data instead. – Neil Lunn Mar 03 '15 at 04:33

1 Answers1

0

You should not need the $project part of the pipeline. You should be get what you need from the $group stage

db.stats.aggregate({ $group: { _id: "$item.type" , total: { $sum: '$hourly' } } });
Kevin Brady
  • 1,684
  • 17
  • 30