Skip to content

Instantly share code, notes, and snippets.

@divjotarora
Last active February 23, 2020 19:57
Show Gist options
  • Save divjotarora/06c5188138456070cee26024f223b3ee to your computer and use it in GitHub Desktop.
Save divjotarora/06c5188138456070cee26024f223b3ee to your computer and use it in GitHub Desktop.
bson.RawValue Marshal/Unmarshal
package main
import (
"fmt"
"go.mongodb.org/mongo-driver/bson"
)
func main() {
// Create an original exmaple document
originalDoc, err := bson.Marshal(bson.D{
{"status", "status1"},
{"fieldA", 10},
{"fieldB", 20},
})
if err != nil {
panic(err)
}
fmt.Printf("original doc: %s\n\n", bson.Raw(originalDoc))
// Unmarshal into intermediary type
var temp map[string]bson.RawValue
if err = bson.Unmarshal(originalDoc, &temp); err != nil {
panic(err)
}
// Decode individual fields for inspection
var status string
if err = temp["status"].Unmarshal(&status); err != nil {
panic(err)
}
fmt.Printf("original status: %s\n\n", status)
// Change the status based on its original value
newStatus := fmt.Sprintf("new%s", status)
newStatusType, newStatusData, err := bson.MarshalValue(newStatus)
if err != nil {
panic(err)
}
temp["status"] = bson.RawValue{
Type: newStatusType,
Value: newStatusData,
}
// Marshal new document and compare
changedDoc, err := bson.Marshal(temp)
if err != nil {
panic(err)
}
fmt.Printf("new doc: %s\n", bson.Raw(changedDoc))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment