如何使用Go官方驱动程序执行addToSet? [英] How to perform addToSet using Go official driver?
本文介绍了如何使用Go官方驱动程序执行addToSet?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用官方的Go MongoDB驱动程序进行 addToSet
操作.
在MongoDB中,我们有一些文档:
{_id:2,项目:电缆",标签:[电子产品",设备"]}
然后执行 addToSet
:
db.inventory.update({_id:2},{$ addToSet:{标签:{$ each:["camera","electronics","accessories"]}}})
结果:
{_id:2项目:电缆",标签:[电子产品",耗材",相机",配件"]}
解决方案
$ addToSet
是一项更新操作,如果要更新单个文档,则可以使用 bson.M
和/或 bson.D
类型来描述您的过滤器和更新文档.
例如:
update:= bson.M {"$ addToSet":bson.M {"tags":bson.M {"$ each":[] string {"camera","electronics","accessories"}},},}res,err:= c.UpdateOne(ctx,bson.M {"_ id":2},更新)
这是一个完整的,可运行的应用程序,可连接到MongoDB服务器并执行上述更新操作:
ctx:= context.Background()客户端,错误:= mongo.Connect(ctx,options.Client().ApplyURI("mongodb://localhost"))如果err!= nil {恐慌}延迟client.Disconnect(ctx)c:= client.Database("dbname").Collection("inventory")更新:= bson.M {"$ addToSet":bson.M {"tags":bson.M {"$ each":[] string {"camera","electronics","accessories"}},},}res,err:= c.UpdateOne(ctx,bson.M {"_ id":2},更新)如果err!= nil {恐慌}fmt.Printf(%+ v",res)
I need to do addToSet
operation using official Go MongoDB driver.
In MongoDB we have some docs:
{ _id: 2, item: "cable", tags: [ "electronics", "supplies" ] }
Then to perform addToSet
:
db.inventory.update(
{ _id: 2 },
{ $addToSet: { tags: { $each: [ "camera", "electronics", "accessories" ] } } }
)
Result:
{
_id: 2,
item: "cable",
tags: [ "electronics", "supplies", "camera", "accessories" ]
}
解决方案
$addToSet
is an update operation, if you want to update a single document, you may use the Collection.UpdateOne()
method.
Use the bson.M
and/or bson.D
types to describe your filters and update document.
For example:
update := bson.M{
"$addToSet": bson.M{
"tags": bson.M{"$each": []string{"camera", "electronics", "accessories"}},
},
}
res, err := c.UpdateOne(ctx, bson.M{"_id": 2}, update)
Here's a complete, runnable app that connects to a MongoDB server and performs the above update operation:
ctx := context.Background()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost"))
if err != nil {
panic(err)
}
defer client.Disconnect(ctx)
c := client.Database("dbname").Collection("inventory")
update := bson.M{
"$addToSet": bson.M{
"tags": bson.M{"$each": []string{"camera", "electronics", "accessories"}},
},
}
res, err := c.UpdateOne(ctx, bson.M{"_id": 2}, update)
if err != nil {
panic(err)
}
fmt.Printf("%+v", res)
这篇关于如何使用Go官方驱动程序执行addToSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文