Search code examples
mongodbgobsonmongo-go

How can i use $set and $inc in a single update call in mongodb golang?


I tried doing this but it didn't work.

update := bson.D{{ "$set": bson.D{ "id": "Q" + addr_to_string }, {"$inc": bson.D{ "amount": amount_int } }}}

Error:

mixture of field:value and value elements in struct literal

This is my initial code:

update := bson.D{{"$set", bson.D{{"id", "Q" + addr_to_string}, {"amount", amount_int}}}}

I try to make amount increment, $inc. How can i do this?


Solution

  • bson.D is to describe a document, an ordered list of properties, where a property is a key-value pair. Properties are described by bson.E which is a simple Go struct holding a Key and Value fields.

    So bson.D is a slice of structs, so a bson.D literal must list struct elements also enclosed in {}.

    Your input may be written as this:

    update := bson.D{
        {
            Key: "$set",
            Value: bson.D{
                {Key: "id", Value: "Q" + addr_to_string},
            },
        },
        {
            Key: "$inc",
            Value: bson.D{
                {Key: "amount", Value: amount_int},
            },
        },
    }
    

    Note that if order doesn't matter (it doesn't matter in this case), it's much more readable and simpler to use bson.M (which is a map) to define your update document:

    update := bson.M{
        "$set": bson.M{
            "id": "Q" + addr_to_string,
        },
        "$inc": bson.M{
            "amount": amount_int,
        },
    }
    

    See related: How to remove the primitive.E composite literal uses unkeyed fields error?