2

I'm using the official mongo driver on golang and trying to aggregate. I want to sort entries based on the multiplication of currency and salary.

import (
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)


func main () {
    //...
    aggregatePipeline := bson.A{}
    aggregatePipeline = append(aggregatePipeline, bson.D{{Key: "$addFields", Value: bson.D{{Key: "trueSalary", Value: bson.D{{"$multiply", bson.A{"salary", "currency"}}}}}}})
    aggregatePipeline = append(aggregatePipeline, bson.D{{"$sort", bson.D{{"trueSalary", -1}}}})
    cursor , _ := myCollection.Aggregate(context.TODO(), aggregatePipeline)
   // cursor returns nil.
}

But cursor returns nil.

My mongo entities all have "salary" and "currency" as Integer.

codemonkey
  • 809
  • 1
  • 9
  • 21

1 Answers1

2

In Go you should always check returned errors. That'll save you a lot of time.

cursor, err := myCollection.Aggregate(context.TODO(), aggregatePipeline)
if err != nil {
    panic(err)
}

This will output something like:

panic: (TypeMismatch) Failed to optimize pipeline :: caused by :: $multiply only supports numeric types, not string

The $multiply operation tries to multiply the salary and currency strings. Obviously this is not what you want, you want to multiply the values of the salary and currency properties, so add a $ sign to them:

aggregatePipeline = append(aggregatePipeline, bson.D{{
    Key: "$addFields",
    Value: bson.D{{
        Key:   "trueSalary",
        Value: bson.D{{"$multiply", bson.A{"$salary", "$currency"}}},
    }},
}})
icza
  • 389,944
  • 63
  • 907
  • 827
  • Thank you very much, I was just checking through mongo driver source code and seeing the exact error code and trying to understand. Like you said, it would be a lot easier to just print err.Thanks! – codemonkey Nov 13 '21 at 21:55