How to use $indexOfArray with Go?

354 views Asked by At

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

There are 1 answers

0
Neil Lunn On BEST ANSWER

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)