如何在Go中使用$indexOfArray函数?

huangapple go评论74阅读模式
英文:

How to use $indexOfArray with Go?

问题

假设我在我的Mongo客户集合中有以下数据:

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

在Mongo Shell中,我可以执行以下命令,它将返回shops数组中shop_name2的索引,即1:

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

然而,在mgo中,以下代码会失败并显示以下错误信息:

Unrecognized expression '$shops.name'

当我查看$indexOfArray的文档时,我注意到第二个参数应该是一个数组。所以我怀疑我可能错误地指定了数组,但是我找不到如何在mgo中设置这个的参考资料。

英文:

Say I have the following data in my mongo customers collection

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

In mongo shell I can do this command and it return the index of shop_name2 in the shops array which is 1

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

However in 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)

fails with the following message

> Unrecognized expression '$shops.name'

When I check the documentation for $indexOfArray I note the second argument is an array. So I suspect I am specifying the array wrong but I can't find any reference on how to set this up for 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)
英文:

The argument to $indexOfArray is simply a list of "string" so []string:

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

Or in full context:

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

huangapple
  • 本文由 发表于 2017年8月29日 21:02:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/45939899.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定