[GODRIVER-1892] Add bson.UnmarshalValue function Created: 19/Feb/21  Updated: 28/Oct/23  Resolved: 01/May/23

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

Type: Improvement Priority: Major - P3
Reporter: Divjot Arora (Inactive) Assignee: Qingyang Hu
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Epic Link: Go Driver 2.0 Prep
Quarter: FY24Q1
Documentation Changes: Not Needed
Documentation Changes Summary:

1. What would you like to communicate to the user about this feature?
2. Would you like the user to see examples of the syntax and/or executable code and its output?
3. Which versions of the driver/connector does this apply to?


 Description   

When marshalling Go types to BSON, users can choose between Marshal(), which assumes the value is a document, and MarshalValue(), which works for all values and returns both a type and a slice of bytes.

For going from BSON bytes to Go, the Unmarshal() function mirrors Marshal() and assumes the input is a document. If the input is some other value like an array, users currently need to do:

val := bson.RawValue{
    Type: bsontype.Array, // or whatever the type is
    Value: bsonBytes,
}
var unmarshalled bson.A
if err := val.Unmarshal(&unmarshalled); err != nil {
   ...
}

We should consider adding a UnmarshalValue() function to mirror MarshalValue().

Definition of done:

  • Add a function bson.UnmarshalValue that, given a BSON type and a byte slice, unmarshals the BSON value into a Go value. Its signature should mirror the bson.MarshalValue API.
    For example:

    func UnmarshalValue(t bsontype.Type, data []byte, val interface{}) error
    



 Comments   
Comment by Chance Dinkins [ 19/Mar/21 ]

This was one of the more annoying things when dealing with the go-mongo-driver. It is resolvable, using codecs, but I've got a growing list of them. In some cases, I'll need them but it would be nice to have the versatility to handle things like this.

 

It would be ideal if Marshal/Unmarshal worked in the same manner as package json in that Marshal/Unmarshal could operate on any type. Short of that, being able to appropriately handle unmarshaling values as described here would be fine.

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