如何在 Go 中使用 $indexOfArray?
How to use $indexOfArray with Go?
假设我的 mongo 客户集合中有以下数据
{customer:"cust1",
shops:[
{name:"shop_name1", sales:200},
{name:"shop_name2", sales:300}
]}
在 mongo shell 中,我可以执行此命令,它 return 商店数组中 shop_name2 的索引为 1
db.customers.aggregate([{"$match":{customer:"cust1"}},{"$project":{"matchedIndex":{"$indexOfArray":["$shops.name","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)
失败并显示以下消息
Unrecognized expression '$shops.name'
当我查看 $indexOfArray 的文档时,我注意到第二个参数是一个数组。所以我怀疑我指定的数组有误,但我找不到任何关于如何为 mgo 设置它的参考。
$indexOfArray
的参数只是 "string" 的列表,所以 []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)
假设我的 mongo 客户集合中有以下数据
{customer:"cust1",
shops:[
{name:"shop_name1", sales:200},
{name:"shop_name2", sales:300}
]}
在 mongo shell 中,我可以执行此命令,它 return 商店数组中 shop_name2 的索引为 1
db.customers.aggregate([{"$match":{customer:"cust1"}},{"$project":{"matchedIndex":{"$indexOfArray":["$shops.name","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)
失败并显示以下消息
Unrecognized expression '$shops.name'
当我查看 $indexOfArray 的文档时,我注意到第二个参数是一个数组。所以我怀疑我指定的数组有误,但我找不到任何关于如何为 mgo 设置它的参考。
$indexOfArray
的参数只是 "string" 的列表,所以 []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)