2017-08-29 79 views
0

說我有我的蒙戈客戶收集提供了以下數據

{customer:"cust1", 
shops:[ 
    {name:"shop_name1", sales:200}, 
    {name:"shop_name2", sales:300} 
]} 

在蒙戈外殼,我可以做到這一點的命令,它的商店陣列爲1

db.customers.aggregate([{"$match":{customer:"cust1"}},{"$project":{"matchedIndex":{"$indexOfArray":["$shops.name","shop_name2"]}}}]) 

然而,在返回shop_name2指數以MgO

err := c.Pipe([]bson.M{{"$match": bson.M{"customer": "cust1"}}, {"$project": bson.M{"matchedIndex": bson.M{"$indexOfArray": []bson.M{{"$shops.name": "shop_name2"}}}}}}).One(&hehehe) 

失敗,出現以下消息

無法識別的表達式「$ shops.name」

當我檢查文檔$indexOfArray我注意到,第二個參數是一個數組。所以我懷疑我指定了錯誤的數組,但我找不到任何有關如何設置mgo的參考。

+1

這不是一個「地圖」,但只是一個普通的列表。 –

回答

2

的參數$indexOfArray簡直是「串」這樣[]string的列表:在完整的上下文

bson.M{"$indexOfArray": []string{"$shops.name", "shop_name2"}} 

或者:

err := c.Pipe([]bson.M{ 
{"$match": bson.M{"customer": "cust1"}}, 
{"$project": bson.M{ 
    "matchedIndex": bson.M{"$indexOfArray": []string{"$shops.name", "shop_name2"}} 
}} 
}).One(&hehehe)