Home > Enterprise >  Mongo Aggregate - $addFields with multiplication
Mongo Aggregate - $addFields with multiplication

Time:11-14

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.

CodePudding user response:

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"}}},
    }},
}})
  • Related