2016-11-11 40 views
0

我已經閱讀了有關在mongo聚合中使用$let的內容。但所有示例僅在$project階段使用$let階段。我想知道$match聚合階段內是否可以使用$let?下面是一個簡單的例子:

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/它應注意什麼? 最好的問候

+0

有什麼目的? – hyades

+0

@hyades使用聚合之外的用戶定義變量動態創建聚合查詢。 – user1665355

+0

可以這樣做,它可以是''顏色':顏色'什麼是確切的目的? – hyades

回答

1

你可以直接使用variables.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 
    ... 
]) 

該查詢在蒙戈執行作爲

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