2

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?

icza
  • 389,944
  • 63
  • 907
  • 827
l33t
  • 133
  • 6

1 Answers1

1

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?

icza
  • 389,944
  • 63
  • 907
  • 827
  • I had one more question. Is it also possible to substract using updateone? I couldn't find that operator. – l33t Aug 09 '22 at 18:12
  • @l33t Use `$inc`, but provide a negative number. Adding a negative number is subtracting. – icza Aug 09 '22 at 18:12