英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论