0

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 

        });
Anirudh
  • 2,767
  • 5
  • 69
  • 119
  • 1
    According to your schema, `"section"` is defined as a "reference" of `ObjectId` to another collection, and the value you are supplying is **not** a valid value for `ObjectId`. Perhaps you mean to be matching on a property of that referenced model instead? You should therefore be looking at [Querying after populate with mongoose](https://stackoverflow.com/a/44688386/2313887), and in particular the recent response I added there related to [`$lookup`](https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/) and more modern MongoDB usage. – Neil Lunn Jul 29 '17 at 12:36
  • @NeilLunn, could you please checkout the update. – Anirudh Aug 14 '17 at 07:58

0 Answers0