Substract two fields in mongodb with Golang

Issue

I run into the problem of wanting to subtract 2 fields from my mongodb database and return them in a variable.

I am using bson.M to perform the operation in golang without any success.

    col2 := db.Collection("products")

pipe2 := []bson.M{
    {"$group": bson.M{
        "_id":   IDUser,
        "total": bson.M{"$subtract": {"$actualPrice", "$oldPrice"}},
    }},
}

cur2, err := col2.Aggregate(ctx, pipe2)

Solution

The $subtract operator requires an array (which may be a slice in Go).

And to add a field to the output document, use the $addFields stage:

pipe2 := []bson.M{
    {"$addFields": bson.M{
        "total": bson.M{"$subtract": []string{"$actualPrice", "$oldPrice"}},
    }},
}

Testing it with the following documents:

{ "_id" : "u1", "actualPrice" : 100, "oldPrice" : 80 }
{ "_id" : "u2", "actualPrice" : 200, "oldPrice" : 190 }

Testing code:

cur2, err := col2.Aggregate(ctx, pipe2)
if err != nil {
    panic(err)
}

var results []bson.M
if err = cur2.All(ctx, &results); err != nil {
    panic(err)
}

fmt.Println(results)

Output:

[map[_id:u1 actualPrice:100 oldPrice:80 total:20] 
 map[_id:u2 actualPrice:200 oldPrice:190 total:10]]

Answered By – icza

Answer Checked By – Cary Denson (GoLangFix Admin)

Leave a Reply

Your email address will not be published.