Search code examples
javascriptmongodbmongodb-queryaggregation-frameworkmongodb-aggregation

Mongodb aggregation, Use value from a variable in the expression of $group _id


I am trying to groups documents by two fields, field1 and field2.

myCollection.aggregate([{
  $group: {
    _id: {
      group1: "$field1",
      group2: "$field2"
    },
    count: {
      $sum: 1
    }
  }
}])

Which works fine producing the expected results.

But I want to re run the above in a loop, each run will have different $field2, so the following is failing, how can I it be done? Thanks

const field3 = 'someValue';  // <<--- will change in every loop run ---

myCollection.aggregate([{
  $group: {
    _id: {
      group1: "$field1",
      group2: "$$field3"  //<<---------------- 
    },
    count: {
      $sum: 1
    }
  }
}])

Solution

  • The following should work for you

    var field3  = 'someValue';
    myCollection.aggregate([{
      $group: {
        _id: {
          group1: "$field1",
          group2: "$" + field3,
        },
        count: {
          $sum: 1
        }
      }
    }])