2017-08-29 73 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)