0

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
  • 1
    It's not a "map" but just a regular list. Commented Aug 29, 2017 at 13:08

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.