[GODRIVER-889] How to Collection.UpdateOne using the result of bson.Marshal? Created: 20/Mar/19  Updated: 11/Sep/19  Resolved: 21/Mar/19

Status: Closed
Project: Go Driver
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Task Priority: Major - P3
Reporter: zhangzhen Assignee: Unassigned
Resolution: Done Votes: 0
Labels: feature
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

For example I have struct like this:

type Profile struct

{ Vip uint32 Lvl uint32 Heros Heros }

type Heros struct

{ HeroIds []uint32 `bson:"hids"` HeroSkills []HeroSkill `bson:"hskls"` }

type HeroSkill struct

{ CounterSkill []string PassiveSkill []string TriggerSkill []string }

 

than, I want to set a record to collection using UpdateOne.

 

id := "alsdkfj"
collection := db.Collection("profiles")

heros := Heros

{ HeroIds: []uint32\{1, 2, 3}

,
}
bsb, err := bson.Marshal(heros)
if err != nil

{ log.Fatal("bson marshal err", err) return }

update := bsonx.Doc{
{"$set", bsonx.Document(bsonx.Doc{{"Vip", bsonx.Int32(3)}})},
{"$set", bsonx.Document(bsonx.Doc{{"Level", bsonx.Int32(10)}})},
{"$set", bsonx.Document(bsonx.Doc{{"Heros", bsb}})}, // this not work
}
res, err := collection.UpdateOne(ctx, bson.D{{"_id", id}}, update, options.Update().SetUpsert(true))

 

I don't find any way to transform []byte to bsonx.Val, so can put the result of bson.Marshal to bsonx.Doc.

If I want to update complex construction conveniently,how should I do?

Please help me, thanks!



 Comments   
Comment by Ian Whalen (Inactive) [ 21/Mar/19 ]

Hey zhangzhen, you should be using bson.D rather than bsonx.Doc - that way you don't have to marshal yourself.

Comment by zhangzhen [ 20/Mar/19 ]

I use mongo golang sdk, https://github.com/mongodb/mongo-go-driver

Generated at Thu Feb 08 08:35:11 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.