Without match I'm getting my required output, when I provide $match value, I'm getting an empty response. What could be the reason for empty response? Is there any different way to call the $match param?
var query = {"section":"324444"}; // 324444 is section schema _id value
Transaction.aggregate({
"$match": query
},{ "$group": { "_id": "$user", "section": { "$first": "$section"}, "amount": { "$sum": { "$cond": ["$credit", "$amount", { "$subtract": [ 0, "$amount" ] }] }} }})
.exec(function(err, transactions)
{
// Transactions List Grouped User wise
});
// Transaction schema
var transSchema = new Schema({
user: {type: mongoose.Schema.Types.ObjectId, ref: 'User',required: true},
section: {type: mongoose.Schema.Types.ObjectId, ref: 'Section',required: true},
amount: { type: Number, required: true},
credit: { type: Boolean, default: true }
created_at: Date
});
// Section schema
var sectionSchema = new Schema({
name: { type: String, required: true},
created_at: Date
});
Update: Tried with the below code, but I get empty response. Also How do I handle when I have to match from 2 or more collections (Say for example I have another Collection named SubSection similar to Section in Transaction Schema)
Code:
Transaction.aggregate({ "$lookup": {
"from": Section.collection.name,
"localField": "section",
"foreignField": "_id",
"as": "section"
}},
{ "$match": {"section._id":"324444"} },
{ "$group": { "_id": "$user", "section": { "$first": "$section"}, "amount": { "$sum": { "$cond": ["$credit", "$amount", { "$subtract": [ 0, "$amount" ] }] }} }})
.exec(function(err, transactions)
{
// Results
});