我正在尝试按两个字段对文档进行分组,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
}
}
}])
最佳答案
以下应该适合你
var field3 = 'someValue';
myCollection.aggregate([{
$group: {
_id: {
group1: "$field1",
group2: "$" + field3,
},
count: {
$sum: 1
}
}
}])
关于javascript - Mongodb 聚合,在 $group _id 的表达式中使用变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39735037/