Mongodb 聚合,使用 $group _id 表达式中变量的值
Mongodb aggregation, Use value from a variable in the expression of $group _id
我正在尝试按两个字段对文档进行分组,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
}
}
}])
我正在尝试按两个字段对文档进行分组,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
}
}
}])