1

我正在尝试按两个字段对文档进行分组,field1并且field2.

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
    }
  }
}])
4

1 回答 1

4

以下内容应该适合您

var field3  = 'someValue';
myCollection.aggregate([{
  $group: {
    _id: {
      group1: "$field1",
      group2: "$" + field3,
    },
    count: {
      $sum: 1
    }
  }
}])
于 2016-09-28T07:42:50.130 回答