Home:ALL Converter>Mongo Aggregate - $addFields with multiplication

Mongo Aggregate - $addFields with multiplication

Ask Time:2021-11-14T05:15:53         Author:codemonkey

Json Formatter

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.

Author:codemonkey,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69958305/mongo-aggregate-addfields-with-multiplication
yy