Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mongo Aggregate – $addFields with multiplication

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"}}},
    }},
}})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading