簡體   English   中英

如何在Go中使用$ indexOfArray?

[英]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

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進行設置的參考。

$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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM