-
-
Save divjotarora/06c5188138456070cee26024f223b3ee to your computer and use it in GitHub Desktop.
bson.RawValue Marshal/Unmarshal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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