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

huangapple go评论87阅读模式
英文:

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

问题

我尝试了这样做,但没有成功。

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

错误信息:

结构体字面量中的字段:值和值元素混合

这是我的初始代码:

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

我尝试使amount增加,即$inc。我该如何做到这一点?

英文:

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?

答案1

得分: 1

bson.D 是用来描述一个文档的,文档是一个有序的属性列表,其中每个属性都是一个键值对。属性由 bson.E 描述,它是一个简单的 Go 结构体,包含 KeyValue 字段。

因此,bson.D 是一个结构体的切片,所以 bson.D 字面量必须列出结构体元素,也要用 {} 括起来。

你的输入可以写成这样:

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},
		},
	},
}

注意,如果顺序不重要(在这种情况下不重要),使用 bson.M(一个映射)来定义更新文档会更易读和简单:

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

参考链接:https://stackoverflow.com/questions/67648046/how-to-remove-the-primitive-e-composite-literal-uses-unkeyed-fields-error/67651664#67651664

英文:

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: https://stackoverflow.com/questions/67648046/how-to-remove-the-primitive-e-composite-literal-uses-unkeyed-fields-error/67651664#67651664

huangapple
  • 本文由 发表于 2022年8月10日 01:53:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/73296180.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定