1

的表达式中使用变量的值我试图按两个字段对文档进行分组,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

以下应该工作,你

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