Mongodb聚合,使用$ group _id表达式中变量的值

时间:2016-09-27 22:02:50

标签: javascript mongodb mongodb-query aggregation-framework mongodb-aggregation

我正在尝试按两个字段field1field2对文档进行分组。

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

哪种方法可以很好地产生预期的结果。

但是我想在循环中重新运行上面的内容,每次运行都会有不同的$field2,所以以下是失败的,我怎么能这样做呢?感谢

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

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

1 个答案:

答案 0 :(得分:1)

以下内容适用于您

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