聚合。在$ match中使用$ let

时间:2016-11-11 13:43:56

标签: mongodb aggregation-framework

我已阅读有关在mongo聚合中使用$let的信息。但是所有示例仅在$let阶段内使用$project。我想知道是否可以在$let聚合阶段内使用$match?这是一个简单的例子:

var Color = "Black";

db.mydata.aggregate([
    { "$match": {     
       "Category": "MyCategory",
       "Location":"London",
       "Color": $let: {
                  vars: {
                    "Color": Color
                  },
                  in: { 
                    "$$Color" 
                  }
                }
}},    
    // other stages as group, project and sort
    ...
])

上述抱怨Expected expression...因此,在$let或其他聚合阶段使用$match是否可能?

EDIT: 这不起作用:

var Color = "Black";

db.mydata.aggregate([
    { "$match": {     
       "Category": "MyCategory",
       "Location":"London",
       "Color": "$$Color"
}},    
    // other stages as group, project and sort
    ...
])

但根据https://docs.mongodb.com/v3.2/reference/aggregation-variables/它应该呢? 最诚挚的问候

1 个答案:

答案 0 :(得分:0)

你可以直接使用变量.Node或mongo shell将负责将字符串替换为变量。无需将它们存储为内部mongo变量或聚合变量。

var Color = "Black";

db.mydata.aggregate([
    { "$match": {     
       "Category": "MyCategory",
       "Location":"London",
       "Color": Color // this would be replaced by string "Black" by node
}},    
    // other stages as group, project and sort
    ...
])

此查询在Mongo中执行

db.mydata.aggregate([
        { "$match": {     
           "Category": "MyCategory",
           "Location":"London",
           "Color": "Black" 
    }},    
        // other stages as group, project and sort
        ...
    ])