Documentation ¶
Overview ¶
Package bson is a library for reading, writing, and manipulating BSON. BSON is a binary serialization format used to store documents and make remote procedure calls in MongoDB. The BSON specification is located at https://bsonspec.org. The BSON library handles marshalling and unmarshalling of values through a configurable codec system. For a description of the codec system and examples of registering custom codecs, see the bsoncodec package. For additional information and usage examples, check out the Work with BSON page in the Go Driver docs site.
Raw BSON ¶
The Raw family of types is used to validate and retrieve elements from a slice of bytes. This type is most useful when you want do lookups on BSON bytes without unmarshaling it into another type.
Example:
var raw bson.Raw = ... // bytes from somewhere err := raw.Validate() if err != nil { return err } val := raw.Lookup("foo") i32, ok := val.Int32OK() // do something with i32...
Native Go Types ¶
The D and M types defined in this package can be used to build representations of BSON using native Go types. D is a slice and M is a map. For more information about the use cases for these types, see the documentation on the type definitions.
Note that a D should not be constructed with duplicate key names, as that can cause undefined server behavior.
Example:
bson.D{{"foo", "bar"}, {"hello", "world"}, {"pi", 3.14159}} bson.M{"foo": "bar", "hello": "world", "pi": 3.14159}
When decoding BSON to a D or M, the following type mappings apply when unmarshalling:
- BSON int32 unmarshals to an int32.
- BSON int64 unmarshals to an int64.
- BSON double unmarshals to a float64.
- BSON string unmarshals to a string.
- BSON boolean unmarshals to a bool.
- BSON embedded document unmarshals to the parent type (i.e. D for a D, M for an M).
- BSON array unmarshals to a bson.A.
- BSON ObjectId unmarshals to a primitive.ObjectID.
- BSON datetime unmarshals to a primitive.DateTime.
- BSON binary unmarshals to a primitive.Binary.
- BSON regular expression unmarshals to a primitive.Regex.
- BSON JavaScript unmarshals to a primitive.JavaScript.
- BSON code with scope unmarshals to a primitive.CodeWithScope.
- BSON timestamp unmarshals to an primitive.Timestamp.
- BSON 128-bit decimal unmarshals to an primitive.Decimal128.
- BSON min key unmarshals to an primitive.MinKey.
- BSON max key unmarshals to an primitive.MaxKey.
- BSON undefined unmarshals to a primitive.Undefined.
- BSON null unmarshals to nil.
- BSON DBPointer unmarshals to a primitive.DBPointer.
- BSON symbol unmarshals to a primitive.Symbol.
The above mappings also apply when marshalling a D or M to BSON. Some other useful marshalling mappings are:
- time.Time marshals to a BSON datetime.
- int8, int16, and int32 marshal to a BSON int32.
- int marshals to a BSON int32 if the value is between math.MinInt32 and math.MaxInt32, inclusive, and a BSON int64 otherwise.
- int64 marshals to BSON int64.
- uint8 and uint16 marshal to a BSON int32.
- uint, uint32, and uint64 marshal to a BSON int32 if the value is between math.MinInt32 and math.MaxInt32, inclusive, and BSON int64 otherwise.
- BSON null and undefined values will unmarshal into the zero value of a field (e.g. unmarshalling a BSON null or undefined value into a string will yield the empty string.).
Structs ¶
Structs can be marshalled/unmarshalled to/from BSON or Extended JSON. When transforming structs to/from BSON or Extended JSON, the following rules apply:
Only exported fields in structs will be marshalled or unmarshalled.
When marshalling a struct, each field will be lowercased to generate the key for the corresponding BSON element. For example, a struct field named "Foo" will generate key "foo". This can be overridden via a struct tag (e.g. `bson:"fooField"` to generate key "fooField" instead).
An embedded struct field is marshalled as a subdocument. The key will be the lowercased name of the field's type.
A pointer field is marshalled as the underlying type if the pointer is non-nil. If the pointer is nil, it is marshalled as a BSON null value.
When unmarshalling, a field of type interface{} will follow the D/M type mappings listed above. BSON documents unmarshalled into an interface{} field will be unmarshalled as a D.
The encoding of each struct field can be customized by the "bson" struct tag.
This tag behavior is configurable, and different struct tag behavior can be configured by initializing a new bsoncodec.StructCodec with the desired tag parser and registering that StructCodec onto the Registry. By default, JSON tags are not honored, but that can be enabled by creating a StructCodec with JSONFallbackStructTagParser, like below:
Example:
structcodec, _ := bsoncodec.NewStructCodec(bsoncodec.JSONFallbackStructTagParser)
The bson tag gives the name of the field, possibly followed by a comma-separated list of options. The name may be empty in order to specify options without overriding the default field name. The following options can be used to configure behavior:
omitempty: If the omitempty struct tag is specified on a field, the field will not be marshalled if it is set to the zero value. Fields with language primitive types such as integers, booleans, and strings are considered empty if their value is equal to the zero value for the type (i.e. 0 for integers, false for booleans, and "" for strings). Slices, maps, and arrays are considered empty if they are of length zero. Interfaces and pointers are considered empty if their value is nil. By default, structs are only considered empty if the struct type implements the bsoncodec.Zeroer interface and the IsZero method returns true. Struct fields whose types do not implement Zeroer are never considered empty and will be marshalled as embedded documents. NOTE: It is recommended that this tag be used for all slice and map fields.
minsize: If the minsize struct tag is specified on a field of type int64, uint, uint32, or uint64 and the value of the field can fit in a signed int32, the field will be serialized as a BSON int32 rather than a BSON int64. For other types, this tag is ignored.
truncate: If the truncate struct tag is specified on a field with a non-float numeric type, BSON doubles unmarshalled into that field will be truncated at the decimal point. For example, if 3.14 is unmarshalled into a field of type int, it will be unmarshalled as 3. If this tag is not specified, the decoder will throw an error if the value cannot be decoded without losing precision. For float64 or non-numeric types, this tag is ignored.
inline: If the inline struct tag is specified for a struct or map field, the field will be "flattened" when marshalling and "un-flattened" when unmarshalling. This means that all of the fields in that struct/map will be pulled up one level and will become top-level fields rather than being fields in a nested document. For example, if a map field named "Map" with value map[string]interface{}{"foo": "bar"} is inlined, the resulting document will be {"foo": "bar"} instead of {"map": {"foo": "bar"}}. There can only be one inlined map field in a struct. If there are duplicated fields in the resulting document when an inlined struct is marshalled, the inlined field will be overwritten. If there are duplicated fields in the resulting document when an inlined map is marshalled, an error will be returned. This tag can be used with fields that are pointers to structs. If an inlined pointer field is nil, it will not be marshalled. For fields that are not maps or structs, this tag is ignored.
Marshalling and Unmarshalling ¶
Manually marshalling and unmarshalling can be done with the Marshal and Unmarshal family of functions.
Index ¶
- Constants
- Variables
- func IndentExtJSON(dst *bytes.Buffer, src []byte, prefix, indent string) error
- func Marshal(val interface{}) ([]byte, error)
- func MarshalAppend(dst []byte, val interface{}) ([]byte, error)deprecated
- func MarshalAppendWithContext(ec bsoncodec.EncodeContext, dst []byte, val interface{}) ([]byte, error)deprecated
- func MarshalAppendWithRegistry(r *bsoncodec.Registry, dst []byte, val interface{}) ([]byte, error)deprecated
- func MarshalExtJSON(val interface{}, canonical, escapeHTML bool) ([]byte, error)
- func MarshalExtJSONAppend(dst []byte, val interface{}, canonical, escapeHTML bool) ([]byte, error)deprecated
- func MarshalExtJSONAppendWithContext(ec bsoncodec.EncodeContext, dst []byte, val interface{}, ...) ([]byte, error)deprecated
- func MarshalExtJSONAppendWithRegistry(r *bsoncodec.Registry, dst []byte, val interface{}, canonical, escapeHTML bool) ([]byte, error)deprecated
- func MarshalExtJSONIndent(val interface{}, canonical, escapeHTML bool, prefix, indent string) ([]byte, error)
- func MarshalExtJSONWithContext(ec bsoncodec.EncodeContext, val interface{}, canonical, escapeHTML bool) ([]byte, error)deprecated
- func MarshalExtJSONWithRegistry(r *bsoncodec.Registry, val interface{}, canonical, escapeHTML bool) ([]byte, error)deprecated
- func MarshalValue(val interface{}) (bsontype.Type, []byte, error)
- func MarshalValueAppend(dst []byte, val interface{}) (bsontype.Type, []byte, error)deprecated
- func MarshalValueAppendWithContext(ec bsoncodec.EncodeContext, dst []byte, val interface{}) (bsontype.Type, []byte, error)deprecated
- func MarshalValueAppendWithRegistry(r *bsoncodec.Registry, dst []byte, val interface{}) (bsontype.Type, []byte, error)deprecated
- func MarshalValueWithContext(ec bsoncodec.EncodeContext, val interface{}) (bsontype.Type, []byte, error)deprecated
- func MarshalValueWithRegistry(r *bsoncodec.Registry, val interface{}) (bsontype.Type, []byte, error)deprecated
- func MarshalWithContext(ec bsoncodec.EncodeContext, val interface{}) ([]byte, error)deprecated
- func MarshalWithRegistry(r *bsoncodec.Registry, val interface{}) ([]byte, error)deprecated
- func NewRegistry() *bsoncodec.Registry
- func NewRegistryBuilder() *bsoncodec.RegistryBuilderdeprecated
- func Unmarshal(data []byte, val interface{}) error
- func UnmarshalExtJSON(data []byte, canonical bool, val interface{}) error
- func UnmarshalExtJSONWithContext(dc bsoncodec.DecodeContext, data []byte, canonical bool, val interface{}) errordeprecated
- func UnmarshalExtJSONWithRegistry(r *bsoncodec.Registry, data []byte, canonical bool, val interface{}) errordeprecated
- func UnmarshalValue(t bsontype.Type, data []byte, val interface{}) error
- func UnmarshalValueWithRegistry(r *bsoncodec.Registry, t bsontype.Type, data []byte, val interface{}) errordeprecated
- func UnmarshalWithContext(dc bsoncodec.DecodeContext, data []byte, val interface{}) errordeprecated
- func UnmarshalWithRegistry(r *bsoncodec.Registry, data []byte, val interface{}) errordeprecated
- type A
- type D
- type Decoder
- func (d *Decoder) AllowTruncatingDoubles()
- func (d *Decoder) BinaryAsSlice()
- func (d *Decoder) Decode(val interface{}) error
- func (d *Decoder) DefaultDocumentD()
- func (d *Decoder) DefaultDocumentM()
- func (d *Decoder) Reset(vr bsonrw.ValueReader) error
- func (d *Decoder) SetContext(dc bsoncodec.DecodeContext) errordeprecated
- func (d *Decoder) SetRegistry(r *bsoncodec.Registry) error
- func (d *Decoder) UseJSONStructTags()
- func (d *Decoder) UseLocalTimeZone()
- func (d *Decoder) ZeroMaps()
- func (d *Decoder) ZeroStructs()
- type E
- type Encoder
- func (e *Encoder) Encode(val interface{}) error
- func (e *Encoder) ErrorOnInlineDuplicates()
- func (e *Encoder) IntMinSize()
- func (e *Encoder) NilByteSliceAsEmpty()
- func (e *Encoder) NilMapAsEmpty()
- func (e *Encoder) NilSliceAsEmpty()
- func (e *Encoder) OmitZeroStruct()
- func (e *Encoder) Reset(vw bsonrw.ValueWriter) error
- func (e *Encoder) SetContext(ec bsoncodec.EncodeContext) errordeprecated
- func (e *Encoder) SetRegistry(r *bsoncodec.Registry) error
- func (e *Encoder) StringifyMapKeysWithFmt()
- func (e *Encoder) UseJSONStructTags()
- type M
- type Marshaler
- type PrimitiveCodecsdeprecated
- func (PrimitiveCodecs) RawDecodeValue(_ bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) errordeprecated
- func (PrimitiveCodecs) RawEncodeValue(_ bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) errordeprecated
- func (PrimitiveCodecs) RawValueDecodeValue(_ bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) errordeprecated
- func (PrimitiveCodecs) RawValueEncodeValue(_ bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) errordeprecated
- func (pc PrimitiveCodecs) RegisterPrimitiveCodecs(rb *bsoncodec.RegistryBuilder)deprecated
- type Raw
- func (r Raw) Elements() ([]RawElement, error)
- func (r Raw) Index(index uint) RawElement
- func (r Raw) IndexErr(index uint) (RawElement, error)
- func (r Raw) Lookup(key ...string) RawValue
- func (r Raw) LookupErr(key ...string) (RawValue, error)
- func (r Raw) String() string
- func (r Raw) Validate() (err error)
- func (r Raw) Values() ([]RawValue, error)
- type RawElement
- type RawValue
- func (rv RawValue) Array() Raw
- func (rv RawValue) ArrayOK() (Raw, bool)
- func (rv RawValue) AsInt32() int32deprecated
- func (rv RawValue) AsInt32OK() (int32, bool)deprecated
- func (rv RawValue) AsInt64() int64
- func (rv RawValue) AsInt64OK() (int64, bool)
- func (rv RawValue) Binary() (subtype byte, data []byte)
- func (rv RawValue) BinaryOK() (subtype byte, data []byte, ok bool)
- func (rv RawValue) Boolean() bool
- func (rv RawValue) BooleanOK() (bool, bool)
- func (rv RawValue) CodeWithScope() (string, Raw)
- func (rv RawValue) CodeWithScopeOK() (string, Raw, bool)
- func (rv RawValue) DBPointer() (string, primitive.ObjectID)
- func (rv RawValue) DBPointerOK() (string, primitive.ObjectID, bool)
- func (rv RawValue) DateTime() int64
- func (rv RawValue) DateTimeOK() (int64, bool)
- func (rv RawValue) DebugString() string
- func (rv RawValue) Decimal128() primitive.Decimal128
- func (rv RawValue) Decimal128OK() (primitive.Decimal128, bool)
- func (rv RawValue) Document() Raw
- func (rv RawValue) DocumentOK() (Raw, bool)
- func (rv RawValue) Double() float64
- func (rv RawValue) DoubleOK() (float64, bool)
- func (rv RawValue) Equal(rv2 RawValue) bool
- func (rv RawValue) Int32() int32
- func (rv RawValue) Int32OK() (int32, bool)
- func (rv RawValue) Int64() int64
- func (rv RawValue) Int64OK() (int64, bool)
- func (rv RawValue) IsNumber() bool
- func (rv RawValue) IsZero() bool
- func (rv RawValue) JavaScript() string
- func (rv RawValue) JavaScriptOK() (string, bool)
- func (rv RawValue) ObjectID() primitive.ObjectID
- func (rv RawValue) ObjectIDOK() (primitive.ObjectID, bool)
- func (rv RawValue) Regex() (pattern, options string)
- func (rv RawValue) RegexOK() (pattern, options string, ok bool)
- func (rv RawValue) String() string
- func (rv RawValue) StringValue() string
- func (rv RawValue) StringValueOK() (string, bool)
- func (rv RawValue) Symbol() string
- func (rv RawValue) SymbolOK() (string, bool)
- func (rv RawValue) Time() time.Time
- func (rv RawValue) TimeOK() (time.Time, bool)
- func (rv RawValue) Timestamp() (t, i uint32)
- func (rv RawValue) TimestampOK() (t, i uint32, ok bool)
- func (rv RawValue) Unmarshal(val interface{}) error
- func (rv RawValue) UnmarshalWithContext(dc *bsoncodec.DecodeContext, val interface{}) error
- func (rv RawValue) UnmarshalWithRegistry(r *bsoncodec.Registry, val interface{}) error
- func (rv RawValue) Validate() error
- type Unmarshaler
- type ValueMarshaler
- type ValueUnmarshaler
- type Zeroer
Examples ¶
- Decoder
- Decoder (ExtendedJSON)
- Decoder (MultipleExtendedJSONDocuments)
- Decoder.DefaultDocumentM
- Decoder.UseJSONStructTags
- Encoder
- Encoder (ExtendedJSON)
- Encoder (MultipleBSONDocuments)
- Encoder (MultipleExtendedJSONDocuments)
- Encoder.StringifyMapKeysWithFmt
- Encoder.UseJSONStructTags
- Raw (Marshal)
- Raw (Unmarshal)
- Raw.Validate
- RawValue (Marshal)
- RawValue (Unmarshal)
Constants ¶
const ( TypeDouble = bsontype.Double TypeString = bsontype.String TypeEmbeddedDocument = bsontype.EmbeddedDocument TypeArray = bsontype.Array TypeBinary = bsontype.Binary TypeUndefined = bsontype.Undefined TypeObjectID = bsontype.ObjectID TypeBoolean = bsontype.Boolean TypeDateTime = bsontype.DateTime TypeNull = bsontype.Null TypeRegex = bsontype.Regex TypeDBPointer = bsontype.DBPointer TypeJavaScript = bsontype.JavaScript TypeSymbol = bsontype.Symbol TypeCodeWithScope = bsontype.CodeWithScope TypeInt32 = bsontype.Int32 TypeTimestamp = bsontype.Timestamp TypeInt64 = bsontype.Int64 TypeDecimal128 = bsontype.Decimal128 TypeMinKey = bsontype.MinKey TypeMaxKey = bsontype.MaxKey )
BSON element types as described in https://bsonspec.org/spec.html.
const ( TypeBinaryGeneric = bsontype.BinaryGeneric TypeBinaryFunction = bsontype.BinaryFunction TypeBinaryBinaryOld = bsontype.BinaryBinaryOld TypeBinaryUUIDOld = bsontype.BinaryUUIDOld TypeBinaryUUID = bsontype.BinaryUUID TypeBinaryMD5 = bsontype.BinaryMD5 TypeBinaryEncrypted = bsontype.BinaryEncrypted TypeBinaryColumn = bsontype.BinaryColumn TypeBinarySensitive = bsontype.BinarySensitive TypeBinaryUserDefined = bsontype.BinaryUserDefined )
BSON binary element subtypes as described in https://bsonspec.org/spec.html.
Variables ¶
var DefaultRegistry = NewRegistry()
DefaultRegistry is the default bsoncodec.Registry. It contains the default codecs and the primitive codecs.
var ErrDecodeToNil = errors.New("cannot Decode to nil value")
ErrDecodeToNil is the error returned when trying to decode to a nil value
var ErrNilContext = errors.New("DecodeContext cannot be nil")
ErrNilContext is returned when the provided DecodeContext is nil.
var ErrNilReader = errors.New("nil reader")
ErrNilReader indicates that an operation was attempted on a nil bson.Reader.
var ErrNilRegistry = errors.New("Registry cannot be nil")
ErrNilRegistry is returned when the provided registry is nil.
Functions ¶
func IndentExtJSON ¶
IndentExtJSON will prefix and indent the provided extended JSON src and append it to dst.
func Marshal ¶
Marshal returns the BSON encoding of val as a BSON document. If val is not a type that can be transformed into a document, MarshalValue should be used instead.
Marshal will use the default registry created by NewRegistry to recursively marshal val into a []byte. Marshal will inspect struct tags and alter the marshaling process accordingly.
func MarshalAppend
deprecated
MarshalAppend will encode val as a BSON document and append the bytes to dst. If dst is not large enough to hold the bytes, it will be grown. If val is not a type that can be transformed into a document, MarshalValueAppend should be used instead.
Deprecated: Use NewEncoder and pass the dst byte slice (wrapped by a bytes.Buffer) into bsonrw.NewBSONValueWriter:
buf := bytes.NewBuffer(dst) vw, err := bsonrw.NewBSONValueWriter(buf) if err != nil { panic(err) } enc, err := bson.NewEncoder(vw) if err != nil { panic(err) }
See Encoder for more examples.
func MarshalAppendWithContext
deprecated
func MarshalAppendWithContext(ec bsoncodec.EncodeContext, dst []byte, val interface{}) ([]byte, error)
MarshalAppendWithContext will encode val as a BSON document using Registry r and EncodeContext ec and append the bytes to dst. If dst is not large enough to hold the bytes, it will be grown. If val is not a type that can be transformed into a document, MarshalValueAppendWithContext should be used instead.
Deprecated: Use NewEncoder, pass the dst byte slice (wrapped by a bytes.Buffer) into bsonrw.NewBSONValueWriter, and use the Encoder configuration methods to set the desired marshal behavior instead:
buf := bytes.NewBuffer(dst) vw, err := bsonrw.NewBSONValueWriter(buf) if err != nil { panic(err) } enc, err := bson.NewEncoder(vw) if err != nil { panic(err) } enc.IntMinSize()
See Encoder for more examples.
func MarshalAppendWithRegistry
deprecated
MarshalAppendWithRegistry will encode val as a BSON document using Registry r and append the bytes to dst. If dst is not large enough to hold the bytes, it will be grown. If val is not a type that can be transformed into a document, MarshalValueAppendWithRegistry should be used instead.
Deprecated: Use NewEncoder, and pass the dst byte slice (wrapped by a bytes.Buffer) into bsonrw.NewBSONValueWriter, and specify the Registry by calling Encoder.SetRegistry instead:
buf := bytes.NewBuffer(dst) vw, err := bsonrw.NewBSONValueWriter(buf) if err != nil { panic(err) } enc, err := bson.NewEncoder(vw) if err != nil { panic(err) } enc.SetRegistry(reg)
See Encoder for more examples.
func MarshalExtJSON ¶
MarshalExtJSON returns the extended JSON encoding of val.
func MarshalExtJSONAppend
deprecated
MarshalExtJSONAppend will append the extended JSON encoding of val to dst. If dst is not large enough to hold the extended JSON encoding of val, dst will be grown.
Deprecated: Use NewEncoder and pass the dst byte slice (wrapped by a bytes.Buffer) into bsonrw.NewExtJSONValueWriter instead:
buf := bytes.NewBuffer(dst) vw, err := bsonrw.NewExtJSONValueWriter(buf, true, false) if err != nil { panic(err) } enc, err := bson.NewEncoder(vw) if err != nil { panic(err) }
See Encoder for more examples.
func MarshalExtJSONAppendWithContext
deprecated
func MarshalExtJSONAppendWithContext(ec bsoncodec.EncodeContext, dst []byte, val interface{}, canonical, escapeHTML bool) ([]byte, error)
MarshalExtJSONAppendWithContext will append the extended JSON encoding of val to dst using Registry r. If dst is not large enough to hold the BSON encoding of val, dst will be grown.
Deprecated: Use NewEncoder, pass the dst byte slice (wrapped by a bytes.Buffer) into bsonrw.NewExtJSONValueWriter, and use the Encoder configuration methods to set the desired marshal behavior instead:
buf := bytes.NewBuffer(dst) vw, err := bsonrw.NewExtJSONValueWriter(buf, true, false) if err != nil { panic(err) } enc, err := bson.NewEncoder(vw) if err != nil { panic(err) } enc.IntMinSize()
See Encoder for more examples.
func MarshalExtJSONAppendWithRegistry
deprecated
func MarshalExtJSONAppendWithRegistry(r *bsoncodec.Registry, dst []byte, val interface{}, canonical, escapeHTML bool) ([]byte, error)
MarshalExtJSONAppendWithRegistry will append the extended JSON encoding of val to dst using Registry r. If dst is not large enough to hold the BSON encoding of val, dst will be grown.
Deprecated: Use NewEncoder, pass the dst byte slice (wrapped by a bytes.Buffer) into bsonrw.NewExtJSONValueWriter, and specify the Registry by calling Encoder.SetRegistry instead:
buf := bytes.NewBuffer(dst) vw, err := bsonrw.NewExtJSONValueWriter(buf, true, false) if err != nil { panic(err) } enc, err := bson.NewEncoder(vw) if err != nil { panic(err) }
See Encoder for more examples.
func MarshalExtJSONIndent ¶
func MarshalExtJSONIndent(val interface{}, canonical, escapeHTML bool, prefix, indent string) ([]byte, error)
MarshalExtJSONIndent returns the extended JSON encoding of val with each line with prefixed and indented.
func MarshalExtJSONWithContext
deprecated
func MarshalExtJSONWithContext(ec bsoncodec.EncodeContext, val interface{}, canonical, escapeHTML bool) ([]byte, error)
MarshalExtJSONWithContext returns the extended JSON encoding of val using Registry r.
Deprecated: Use NewEncoder and use the Encoder configuration methods to set the desired marshal behavior instead:
buf := new(bytes.Buffer) vw, err := bsonrw.NewBSONValueWriter(buf) if err != nil { panic(err) } enc, err := bson.NewEncoder(vw) if err != nil { panic(err) } enc.IntMinSize()
See Encoder for more examples.
func MarshalExtJSONWithRegistry
deprecated
func MarshalExtJSONWithRegistry(r *bsoncodec.Registry, val interface{}, canonical, escapeHTML bool) ([]byte, error)
MarshalExtJSONWithRegistry returns the extended JSON encoding of val using Registry r.
Deprecated: Use NewEncoder and specify the Registry by calling Encoder.SetRegistry instead:
buf := new(bytes.Buffer) vw, err := bsonrw.NewBSONValueWriter(buf) if err != nil { panic(err) } enc, err := bson.NewEncoder(vw) if err != nil { panic(err) } enc.SetRegistry(reg)
See Encoder for more examples.
func MarshalValue ¶
MarshalValue returns the BSON encoding of val.
MarshalValue will use bson.DefaultRegistry to transform val into a BSON value. If val is a struct, this function will inspect struct tags and alter the marshalling process accordingly.
func MarshalValueAppend
deprecated
MarshalValueAppend will append the BSON encoding of val to dst. If dst is not large enough to hold the BSON encoding of val, dst will be grown.
Deprecated: Appending individual BSON elements to an existing slice will not be supported in Go Driver 2.0.
func MarshalValueAppendWithContext
deprecated
func MarshalValueAppendWithContext(ec bsoncodec.EncodeContext, dst []byte, val interface{}) (bsontype.Type, []byte, error)
MarshalValueAppendWithContext will append the BSON encoding of val to dst using EncodeContext ec. If dst is not large enough to hold the BSON encoding of val, dst will be grown.
Deprecated: Appending individual BSON elements to an existing slice will not be supported in Go Driver 2.0.
func MarshalValueAppendWithRegistry
deprecated
func MarshalValueAppendWithRegistry(r *bsoncodec.Registry, dst []byte, val interface{}) (bsontype.Type, []byte, error)
MarshalValueAppendWithRegistry will append the BSON encoding of val to dst using Registry r. If dst is not large enough to hold the BSON encoding of val, dst will be grown.
Deprecated: Appending individual BSON elements to an existing slice will not be supported in Go Driver 2.0.
func MarshalValueWithContext
deprecated
func MarshalValueWithContext(ec bsoncodec.EncodeContext, val interface{}) (bsontype.Type, []byte, error)
MarshalValueWithContext returns the BSON encoding of val using EncodeContext ec.
Deprecated: Using a custom EncodeContext to marshal individual BSON elements will not be supported in Go Driver 2.0.
func MarshalValueWithRegistry
deprecated
func MarshalWithContext
deprecated
func MarshalWithContext(ec bsoncodec.EncodeContext, val interface{}) ([]byte, error)
MarshalWithContext returns the BSON encoding of val as a BSON document using EncodeContext ec. If val is not a type that can be transformed into a document, MarshalValueWithContext should be used instead.
Deprecated: Use NewEncoder and use the Encoder configuration methods to set the desired marshal behavior instead:
buf := bytes.NewBuffer(dst) vw, err := bsonrw.NewBSONValueWriter(buf) if err != nil { panic(err) } enc, err := bson.NewEncoder(vw) if err != nil { panic(err) } enc.IntMinSize()
See Encoder for more examples.
func MarshalWithRegistry
deprecated
MarshalWithRegistry returns the BSON encoding of val as a BSON document. If val is not a type that can be transformed into a document, MarshalValueWithRegistry should be used instead.
Deprecated: Use NewEncoder and specify the Registry by calling Encoder.SetRegistry instead:
buf := new(bytes.Buffer) vw, err := bsonrw.NewBSONValueWriter(buf) if err != nil { panic(err) } enc, err := bson.NewEncoder(vw) if err != nil { panic(err) } enc.SetRegistry(reg)
See Encoder for more examples.
func NewRegistry ¶
NewRegistry creates a new Registry configured with the default encoders and decoders from the bsoncodec.DefaultValueEncoders and bsoncodec.DefaultValueDecoders types and the PrimitiveCodecs type in this package.
func NewRegistryBuilder
deprecated
func NewRegistryBuilder() *bsoncodec.RegistryBuilder
NewRegistryBuilder creates a new RegistryBuilder configured with the default encoders and decoders from the bsoncodec.DefaultValueEncoders and bsoncodec.DefaultValueDecoders types and the PrimitiveCodecs type in this package.
Deprecated: Use NewRegistry instead.
func Unmarshal ¶
Unmarshal parses the BSON-encoded data and stores the result in the value pointed to by val. If val is nil or not a pointer, Unmarshal returns InvalidUnmarshalError.
func UnmarshalExtJSON ¶
UnmarshalExtJSON parses the extended JSON-encoded data and stores the result in the value pointed to by val. If val is nil or not a pointer, Unmarshal returns InvalidUnmarshalError.
func UnmarshalExtJSONWithContext
deprecated
func UnmarshalExtJSONWithContext(dc bsoncodec.DecodeContext, data []byte, canonical bool, val interface{}) error
UnmarshalExtJSONWithContext parses the extended JSON-encoded data using DecodeContext dc and stores the result in the value pointed to by val. If val is nil or not a pointer, UnmarshalWithRegistry returns InvalidUnmarshalError.
Deprecated: Use NewDecoder and use the Decoder configuration methods to set the desired unmarshal behavior instead:
vr, err := bsonrw.NewExtJSONValueReader(bytes.NewReader(data), true) if err != nil { panic(err) } dec, err := bson.NewDecoder(vr) if err != nil { panic(err) } dec.DefaultDocumentM()
See Decoder for more examples.
func UnmarshalExtJSONWithRegistry
deprecated
func UnmarshalExtJSONWithRegistry(r *bsoncodec.Registry, data []byte, canonical bool, val interface{}) error
UnmarshalExtJSONWithRegistry parses the extended JSON-encoded data using Registry r and stores the result in the value pointed to by val. If val is nil or not a pointer, UnmarshalWithRegistry returns InvalidUnmarshalError.
Deprecated: Use NewDecoder and specify the Registry by calling Decoder.SetRegistry instead:
vr, err := bsonrw.NewExtJSONValueReader(bytes.NewReader(data), true) if err != nil { panic(err) } dec, err := bson.NewDecoder(vr) if err != nil { panic(err) } dec.SetRegistry(reg)
See Decoder for more examples.
func UnmarshalValue ¶
UnmarshalValue parses the BSON value of type t with bson.DefaultRegistry and stores the result in the value pointed to by val. If val is nil or not a pointer, UnmarshalValue returns an error.
func UnmarshalValueWithRegistry
deprecated
func UnmarshalValueWithRegistry(r *bsoncodec.Registry, t bsontype.Type, data []byte, val interface{}) error
UnmarshalValueWithRegistry parses the BSON value of type t with registry r and stores the result in the value pointed to by val. If val is nil or not a pointer, UnmarshalValue returns an error.
Deprecated: Using a custom registry to unmarshal individual BSON values will not be supported in Go Driver 2.0.
func UnmarshalWithContext
deprecated
func UnmarshalWithContext(dc bsoncodec.DecodeContext, data []byte, val interface{}) error
UnmarshalWithContext parses the BSON-encoded data using DecodeContext dc and stores the result in the value pointed to by val. If val is nil or not a pointer, UnmarshalWithRegistry returns InvalidUnmarshalError.
Deprecated: Use NewDecoder and use the Decoder configuration methods to set the desired unmarshal behavior instead:
dec, err := bson.NewDecoder(bsonrw.NewBSONDocumentReader(data)) if err != nil { panic(err) } dec.DefaultDocumentM()
See Decoder for more examples.
func UnmarshalWithRegistry
deprecated
UnmarshalWithRegistry parses the BSON-encoded data using Registry r and stores the result in the value pointed to by val. If val is nil or not a pointer, UnmarshalWithRegistry returns InvalidUnmarshalError.
Deprecated: Use NewDecoder and specify the Registry by calling Decoder.SetRegistry instead:
dec, err := bson.NewDecoder(bsonrw.NewBSONDocumentReader(data)) if err != nil { panic(err) } dec.SetRegistry(reg)
See Decoder for more examples.
Types ¶
type A ¶
An A is an ordered representation of a BSON array.
Example usage:
bson.A{"bar", "world", 3.14159, bson.D{{"qux", 12345}}}
type D ¶
D is an ordered representation of a BSON document. This type should be used when the order of the elements matters, such as MongoDB command documents. If the order of the elements does not matter, an M should be used instead.
A D should not be constructed with duplicate key names, as that can cause undefined server behavior.
Example usage:
bson.D{{"foo", "bar"}, {"hello", "world"}, {"pi", 3.14159}}
type Decoder ¶
type Decoder struct {
// contains filtered or unexported fields
}
A Decoder reads and decodes BSON documents from a stream. It reads from a bsonrw.ValueReader as the source of BSON data.
Example ¶
package main import ( "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/bsonrw" ) func main() { // Marshal a BSON document that contains the name, SKU, and price (in cents) // of a product. doc := bson.D{ {Key: "name", Value: "Cereal Rounds"}, {Key: "sku", Value: "AB12345"}, {Key: "price_cents", Value: 399}, } data, err := bson.Marshal(doc) if err != nil { panic(err) } // Create a Decoder that reads the marshaled BSON document and use it to // unmarshal the document into a Product struct. decoder, err := bson.NewDecoder(bsonrw.NewBSONDocumentReader(data)) if err != nil { panic(err) } type Product struct { Name string `bson:"name"` SKU string `bson:"sku"` Price int64 `bson:"price_cents"` } var res Product err = decoder.Decode(&res) if err != nil { panic(err) } fmt.Printf("%+v\n", res) }
Output: {Name:Cereal Rounds SKU:AB12345 Price:399}
Example (ExtendedJSON) ¶
package main import ( "bytes" "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/bsonrw" ) func main() { // Define an Extended JSON document that contains the name, SKU, and price // (in cents) of a product. data := []byte(`{"name":"Cereal Rounds","sku":"AB12345","price_cents":{"$numberLong":"399"}}`) // Create a Decoder that reads the Extended JSON document and use it to // unmarshal the document into a Product struct. vr, err := bsonrw.NewExtJSONValueReader(bytes.NewReader(data), true) if err != nil { panic(err) } decoder, err := bson.NewDecoder(vr) if err != nil { panic(err) } type Product struct { Name string `bson:"name"` SKU string `bson:"sku"` Price int64 `bson:"price_cents"` } var res Product err = decoder.Decode(&res) if err != nil { panic(err) } fmt.Printf("%+v\n", res) }
Output: {Name:Cereal Rounds SKU:AB12345 Price:399}
Example (MultipleExtendedJSONDocuments) ¶
package main import ( "bytes" "errors" "fmt" "io" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/bsonrw" ) func main() { // Define a newline-separated sequence of Extended JSON documents that // contain X,Y coordinates. data := []byte(` {"x":{"$numberInt":"0"},"y":{"$numberInt":"0"}} {"x":{"$numberInt":"1"},"y":{"$numberInt":"1"}} {"x":{"$numberInt":"2"},"y":{"$numberInt":"2"}} {"x":{"$numberInt":"3"},"y":{"$numberInt":"3"}} {"x":{"$numberInt":"4"},"y":{"$numberInt":"4"}} `) // Create a Decoder that reads the Extended JSON documents and use it to // unmarshal the documents Coordinate structs. vr, err := bsonrw.NewExtJSONValueReader(bytes.NewReader(data), true) if err != nil { panic(err) } decoder, err := bson.NewDecoder(vr) if err != nil { panic(err) } type Coordinate struct { X int Y int } // Read and unmarshal each Extended JSON document from the sequence. If // Decode returns error io.EOF, that means the Decoder has reached the end // of the input, so break the loop. for { var res Coordinate err = decoder.Decode(&res) if errors.Is(err, io.EOF) { break } if err != nil { panic(err) } fmt.Printf("%+v\n", res) } }
Output: {X:0 Y:0} {X:1 Y:1} {X:2 Y:2} {X:3 Y:3} {X:4 Y:4}
func NewDecoder ¶
func NewDecoder(vr bsonrw.ValueReader) (*Decoder, error)
NewDecoder returns a new decoder that uses the DefaultRegistry to read from vr.
func NewDecoderWithContext
deprecated
func NewDecoderWithContext(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader) (*Decoder, error)
NewDecoderWithContext returns a new decoder that uses DecodeContext dc to read from vr.
Deprecated: Use NewDecoder and use the Decoder configuration methods set the desired unmarshal behavior instead.
func (*Decoder) AllowTruncatingDoubles ¶
func (d *Decoder) AllowTruncatingDoubles()
AllowTruncatingDoubles causes the Decoder to truncate the fractional part of BSON "double" values when attempting to unmarshal them into a Go integer (int, int8, int16, int32, or int64) struct field. The truncation logic does not apply to BSON "decimal128" values.
func (*Decoder) BinaryAsSlice ¶
func (d *Decoder) BinaryAsSlice()
BinaryAsSlice causes the Decoder to unmarshal BSON binary field values that are the "Generic" or "Old" BSON binary subtype as a Go byte slice instead of a primitive.Binary.
func (*Decoder) Decode ¶
Decode reads the next BSON document from the stream and decodes it into the value pointed to by val.
See Unmarshal for details about BSON unmarshaling behavior.
func (*Decoder) DefaultDocumentD ¶
func (d *Decoder) DefaultDocumentD()
DefaultDocumentD causes the Decoder to always unmarshal documents into the primitive.D type. This behavior is restricted to data typed as "interface{}" or "map[string]interface{}".
func (*Decoder) DefaultDocumentM ¶
func (d *Decoder) DefaultDocumentM()
DefaultDocumentM causes the Decoder to always unmarshal documents into the primitive.M type. This behavior is restricted to data typed as "interface{}" or "map[string]interface{}".
Example ¶
package main import ( "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/bsonrw" ) func main() { // Marshal a BSON document that contains a city name and a nested document // with various city properties. doc := bson.D{ {Key: "name", Value: "New York"}, {Key: "properties", Value: bson.D{ {Key: "state", Value: "NY"}, {Key: "population", Value: 8_804_190}, {Key: "elevation", Value: 10}, }}, } data, err := bson.Marshal(doc) if err != nil { panic(err) } // Create a Decoder that reads the marshaled BSON document and use it to unmarshal the document // into a City struct. decoder, err := bson.NewDecoder(bsonrw.NewBSONDocumentReader(data)) if err != nil { panic(err) } type City struct { Name string `bson:"name"` Properties interface{} `bson:"properties"` } // Configure the Decoder to default to decoding BSON documents as the bson.M // type if the decode destination has no type information. The Properties // field in the City struct will be decoded as a "bson.M" (i.e. map) instead // of the default "bson.D". decoder.DefaultDocumentM() var res City err = decoder.Decode(&res) if err != nil { panic(err) } fmt.Printf("%+v\n", res) }
Output: {Name:New York Properties:map[elevation:10 population:8804190 state:NY]}
func (*Decoder) Reset ¶
func (d *Decoder) Reset(vr bsonrw.ValueReader) error
Reset will reset the state of the decoder, using the same *DecodeContext used in the original construction but using vr for reading.
func (*Decoder) SetContext
deprecated
func (d *Decoder) SetContext(dc bsoncodec.DecodeContext) error
SetContext replaces the current registry of the decoder with dc.
Deprecated: Use the Decoder configuration methods to set the desired unmarshal behavior instead.
func (*Decoder) SetRegistry ¶
SetRegistry replaces the current registry of the decoder with r.
func (*Decoder) UseJSONStructTags ¶
func (d *Decoder) UseJSONStructTags()
UseJSONStructTags causes the Decoder to fall back to using the "json" struct tag if a "bson" struct tag is not specified.
Example ¶
package main import ( "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/bsonrw" ) func main() { // Marshal a BSON document that contains the name, SKU, and price (in cents) // of a product. doc := bson.D{ {Key: "name", Value: "Cereal Rounds"}, {Key: "sku", Value: "AB12345"}, {Key: "price_cents", Value: 399}, } data, err := bson.Marshal(doc) if err != nil { panic(err) } // Create a Decoder that reads the marshaled BSON document and use it to // unmarshal the document into a Product struct. decoder, err := bson.NewDecoder(bsonrw.NewBSONDocumentReader(data)) if err != nil { panic(err) } type Product struct { Name string `json:"name"` SKU string `json:"sku"` Price int64 `json:"price_cents"` } // Configure the Decoder to use "json" struct tags when decoding if "bson" // struct tags are not present. decoder.UseJSONStructTags() var res Product err = decoder.Decode(&res) if err != nil { panic(err) } fmt.Printf("%+v\n", res) }
Output: {Name:Cereal Rounds SKU:AB12345 Price:399}
func (*Decoder) UseLocalTimeZone ¶
func (d *Decoder) UseLocalTimeZone()
UseLocalTimeZone causes the Decoder to unmarshal time.Time values in the local timezone instead of the UTC timezone.
func (*Decoder) ZeroMaps ¶
func (d *Decoder) ZeroMaps()
ZeroMaps causes the Decoder to delete any existing values from Go maps in the destination value passed to Decode before unmarshaling BSON documents into them.
func (*Decoder) ZeroStructs ¶
func (d *Decoder) ZeroStructs()
ZeroStructs causes the Decoder to delete any existing values from Go structs in the destination value passed to Decode before unmarshaling BSON documents into them.
type Encoder ¶
type Encoder struct {
// contains filtered or unexported fields
}
An Encoder writes a serialization format to an output stream. It writes to a bsonrw.ValueWriter as the destination of BSON data.
Example ¶
package main import ( "bytes" "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/bsonrw" ) func main() { // Create an Encoder that writes BSON values to a bytes.Buffer. buf := new(bytes.Buffer) vw, err := bsonrw.NewBSONValueWriter(buf) if err != nil { panic(err) } encoder, err := bson.NewEncoder(vw) if err != nil { panic(err) } type Product struct { Name string `bson:"name"` SKU string `bson:"sku"` Price int64 `bson:"price_cents"` } // Use the Encoder to marshal a BSON document that contains the name, SKU, // and price (in cents) of a product. product := Product{ Name: "Cereal Rounds", SKU: "AB12345", Price: 399, } err = encoder.Encode(product) if err != nil { panic(err) } // Print the BSON document as Extended JSON by converting it to bson.Raw. fmt.Println(bson.Raw(buf.Bytes()).String()) }
Output: {"name": "Cereal Rounds","sku": "AB12345","price_cents": {"$numberLong":"399"}}
Example (ExtendedJSON) ¶
package main import ( "bytes" "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/bsonrw" ) func main() { // Create an Encoder that writes canonical Extended JSON values to a // bytes.Buffer. buf := new(bytes.Buffer) vw, err := bsonrw.NewExtJSONValueWriter(buf, true, false) if err != nil { panic(err) } encoder, err := bson.NewEncoder(vw) if err != nil { panic(err) } type Product struct { Name string `bson:"name"` SKU string `bson:"sku"` Price int64 `bson:"price_cents"` } // Use the Encoder to marshal a BSON document that contains the name, SKU, // and price (in cents) of a product. product := Product{ Name: "Cereal Rounds", SKU: "AB12345", Price: 399, } err = encoder.Encode(product) if err != nil { panic(err) } fmt.Println(buf.String()) }
Output: {"name":"Cereal Rounds","sku":"AB12345","price_cents":{"$numberLong":"399"}}
Example (MultipleBSONDocuments) ¶
package main import ( "bytes" "errors" "fmt" "io" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/bsonrw" ) func main() { // Create an Encoder that writes BSON values to a bytes.Buffer. buf := new(bytes.Buffer) vw, err := bsonrw.NewBSONValueWriter(buf) if err != nil { panic(err) } encoder, err := bson.NewEncoder(vw) if err != nil { panic(err) } type Coordinate struct { X int Y int } // Use the encoder to marshal 5 Coordinate values as a sequence of BSON // documents. for i := 0; i < 5; i++ { err := encoder.Encode(Coordinate{ X: i, Y: i + 1, }) if err != nil { panic(err) } } // Read each marshaled BSON document from the buffer and print them as // Extended JSON by converting them to bson.Raw. for { doc, err := bson.ReadDocument(buf) if errors.Is(err, io.EOF) { return } if err != nil { panic(err) } fmt.Println(doc.String()) } }
Output: {"x": {"$numberInt":"0"},"y": {"$numberInt":"1"}} {"x": {"$numberInt":"1"},"y": {"$numberInt":"2"}} {"x": {"$numberInt":"2"},"y": {"$numberInt":"3"}} {"x": {"$numberInt":"3"},"y": {"$numberInt":"4"}} {"x": {"$numberInt":"4"},"y": {"$numberInt":"5"}}
Example (MultipleExtendedJSONDocuments) ¶
package main import ( "bytes" "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/bsonrw" ) func main() { // Create an Encoder that writes canonical Extended JSON values to a // bytes.Buffer. buf := new(bytes.Buffer) vw, err := bsonrw.NewExtJSONValueWriter(buf, true, false) if err != nil { panic(err) } encoder, err := bson.NewEncoder(vw) if err != nil { panic(err) } type Coordinate struct { X int Y int } // Use the encoder to marshal 5 Coordinate values as a sequence of Extended // JSON documents. for i := 0; i < 5; i++ { err := encoder.Encode(Coordinate{ X: i, Y: i + 1, }) if err != nil { panic(err) } } fmt.Println(buf.String()) }
Output: {"x":{"$numberInt":"0"},"y":{"$numberInt":"1"}} {"x":{"$numberInt":"1"},"y":{"$numberInt":"2"}} {"x":{"$numberInt":"2"},"y":{"$numberInt":"3"}} {"x":{"$numberInt":"3"},"y":{"$numberInt":"4"}} {"x":{"$numberInt":"4"},"y":{"$numberInt":"5"}}
func NewEncoder ¶
func NewEncoder(vw bsonrw.ValueWriter) (*Encoder, error)
NewEncoder returns a new encoder that uses the DefaultRegistry to write to vw.
func NewEncoderWithContext
deprecated
func NewEncoderWithContext(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter) (*Encoder, error)
NewEncoderWithContext returns a new encoder that uses EncodeContext ec to write to vw.
Deprecated: Use NewEncoder and use the Encoder configuration methods to set the desired marshal behavior instead.
func (*Encoder) Encode ¶
Encode writes the BSON encoding of val to the stream.
See Marshal for details about BSON marshaling behavior.
func (*Encoder) ErrorOnInlineDuplicates ¶
func (e *Encoder) ErrorOnInlineDuplicates()
ErrorOnInlineDuplicates causes the Encoder to return an error if there is a duplicate field in the marshaled BSON when the "inline" struct tag option is set.
func (*Encoder) IntMinSize ¶
func (e *Encoder) IntMinSize()
IntMinSize causes the Encoder to marshal Go integer values (int, int8, int16, int32, int64, uint, uint8, uint16, uint32, or uint64) as the minimum BSON int size (either 32 or 64 bits) that can represent the integer value.
func (*Encoder) NilByteSliceAsEmpty ¶
func (e *Encoder) NilByteSliceAsEmpty()
NilByteSliceAsEmpty causes the Encoder to marshal nil Go byte slices as empty BSON binary values instead of BSON null.
func (*Encoder) NilMapAsEmpty ¶
func (e *Encoder) NilMapAsEmpty()
NilMapAsEmpty causes the Encoder to marshal nil Go maps as empty BSON documents instead of BSON null.
func (*Encoder) NilSliceAsEmpty ¶
func (e *Encoder) NilSliceAsEmpty()
NilSliceAsEmpty causes the Encoder to marshal nil Go slices as empty BSON arrays instead of BSON null.
func (*Encoder) OmitZeroStruct ¶
func (e *Encoder) OmitZeroStruct()
OmitZeroStruct causes the Encoder to consider the zero value for a struct (e.g. MyStruct{}) as empty and omit it from the marshaled BSON when the "omitempty" struct tag option is set.
Note that the Encoder only examines exported struct fields when determining if a struct is the zero value. It considers pointers to a zero struct value (e.g. &MyStruct{}) not empty.
func (*Encoder) Reset ¶
func (e *Encoder) Reset(vw bsonrw.ValueWriter) error
Reset will reset the state of the Encoder, using the same *EncodeContext used in the original construction but using vw.
func (*Encoder) SetContext
deprecated
func (e *Encoder) SetContext(ec bsoncodec.EncodeContext) error
SetContext replaces the current EncodeContext of the encoder with ec.
Deprecated: Use the Encoder configuration methods set the desired marshal behavior instead.
func (*Encoder) SetRegistry ¶
SetRegistry replaces the current registry of the Encoder with r.
func (*Encoder) StringifyMapKeysWithFmt ¶
func (e *Encoder) StringifyMapKeysWithFmt()
StringifyMapKeysWithFmt causes the Encoder to convert Go map keys to BSON document field name strings using fmt.Sprint instead of the default string conversion logic.
Example ¶
package main import ( "bytes" "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/bsonrw" ) type CityState struct { City string State string } func (k CityState) String() string { return fmt.Sprintf("%s, %s", k.City, k.State) } func main() { // Create an Encoder that writes BSON values to a bytes.Buffer. buf := new(bytes.Buffer) vw, err := bsonrw.NewBSONValueWriter(buf) if err != nil { panic(err) } encoder, err := bson.NewEncoder(vw) if err != nil { panic(err) } // Configure the Encoder to convert Go map keys to BSON document field names // using fmt.Sprintf instead of the default string conversion logic. encoder.StringifyMapKeysWithFmt() // Use the Encoder to marshal a BSON document that contains is a map of // city and state to a list of zip codes in that city. zipCodes := map[CityState][]int{ {City: "New York", State: "NY"}: {10001, 10301, 10451}, } err = encoder.Encode(zipCodes) if err != nil { panic(err) } // Print the BSON document as Extended JSON by converting it to bson.Raw. fmt.Println(bson.Raw(buf.Bytes()).String()) }
Output: {"New York, NY": [{"$numberInt":"10001"},{"$numberInt":"10301"},{"$numberInt":"10451"}]}
func (*Encoder) UseJSONStructTags ¶
func (e *Encoder) UseJSONStructTags()
UseJSONStructTags causes the Encoder to fall back to using the "json" struct tag if a "bson" struct tag is not specified.
Example ¶
package main import ( "bytes" "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/bsonrw" ) func main() { // Create an Encoder that writes BSON values to a bytes.Buffer. buf := new(bytes.Buffer) vw, err := bsonrw.NewBSONValueWriter(buf) if err != nil { panic(err) } encoder, err := bson.NewEncoder(vw) if err != nil { panic(err) } type Product struct { Name string `json:"name"` SKU string `json:"sku"` Price int64 `json:"price_cents"` } // Configure the Encoder to use "json" struct tags when decoding if "bson" // struct tags are not present. encoder.UseJSONStructTags() // Use the Encoder to marshal a BSON document that contains the name, SKU, // and price (in cents) of a product. product := Product{ Name: "Cereal Rounds", SKU: "AB12345", Price: 399, } err = encoder.Encode(product) if err != nil { panic(err) } // Print the BSON document as Extended JSON by converting it to bson.Raw. fmt.Println(bson.Raw(buf.Bytes()).String()) }
Output: {"name": "Cereal Rounds","sku": "AB12345","price_cents": {"$numberLong":"399"}}
type M ¶
M is an unordered representation of a BSON document. This type should be used when the order of the elements does not matter. This type is handled as a regular map[string]interface{} when encoding and decoding. Elements will be serialized in an undefined, random order. If the order of the elements matters, a D should be used instead.
Example usage:
bson.M{"foo": "bar", "hello": "world", "pi": 3.14159}
type Marshaler ¶
Marshaler is the interface implemented by types that can marshal themselves into a valid BSON document.
Implementations of Marshaler must return a full BSON document. To create custom BSON marshaling behavior for individual values in a BSON document, implement the ValueMarshaler interface instead.
type PrimitiveCodecs
deprecated
type PrimitiveCodecs struct{}
PrimitiveCodecs is a namespace for all of the default bsoncodec.Codecs for the primitive types defined in this package.
Deprecated: Use bson.NewRegistry to get a registry with all primitive encoders and decoders registered.
func (PrimitiveCodecs) RawDecodeValue
deprecated
func (PrimitiveCodecs) RawDecodeValue(_ bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error
RawDecodeValue is the ValueDecoderFunc for Reader.
Deprecated: Use bson.NewRegistry to get a registry with all primitive encoders and decoders registered.
func (PrimitiveCodecs) RawEncodeValue
deprecated
func (PrimitiveCodecs) RawEncodeValue(_ bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error
RawEncodeValue is the ValueEncoderFunc for Reader.
Deprecated: Use bson.NewRegistry to get a registry with all primitive encoders and decoders registered.
func (PrimitiveCodecs) RawValueDecodeValue
deprecated
func (PrimitiveCodecs) RawValueDecodeValue(_ bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error
RawValueDecodeValue is the ValueDecoderFunc for RawValue.
Deprecated: Use bson.NewRegistry to get a registry with all primitive encoders and decoders registered.
func (PrimitiveCodecs) RawValueEncodeValue
deprecated
func (PrimitiveCodecs) RawValueEncodeValue(_ bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error
RawValueEncodeValue is the ValueEncoderFunc for RawValue.
If the RawValue's Type is "invalid" and the RawValue's Value is not empty or nil, then this method will return an error.
Deprecated: Use bson.NewRegistry to get a registry with all primitive encoders and decoders registered.
func (PrimitiveCodecs) RegisterPrimitiveCodecs
deprecated
func (pc PrimitiveCodecs) RegisterPrimitiveCodecs(rb *bsoncodec.RegistryBuilder)
RegisterPrimitiveCodecs will register the encode and decode methods attached to PrimitiveCodecs with the provided RegistryBuilder. if rb is nil, a new empty RegistryBuilder will be created.
Deprecated: Use bson.NewRegistry to get a registry with all primitive encoders and decoders registered.
type Raw ¶
type Raw []byte
Raw is a raw encoded BSON document. It can be used to delay BSON document decoding or precompute a BSON encoded document.
A Raw must be a full BSON document. Use the RawValue type for individual BSON values.
Example (Marshal) ¶
This example uses Raw to add a precomputed BSON document during marshal.
package main import ( "fmt" "go.mongodb.org/mongo-driver/bson" ) func main() { precomputed, err := bson.Marshal(bson.M{"Precomputed": true}) if err != nil { panic(err) } msg := struct { Message string Metadata bson.Raw }{ Message: "Hello World!", Metadata: precomputed, } b, err := bson.Marshal(msg) if err != nil { panic(err) } // Print the Extended JSON by converting BSON to bson.Raw. fmt.Println(bson.Raw(b).String()) }
Output: {"message": "Hello World!","metadata": {"Precomputed": true}}
Example (Unmarshal) ¶
This example uses Raw to skip parsing a nested document in a BSON message.
package main import ( "fmt" "go.mongodb.org/mongo-driver/bson" ) func main() { b, err := bson.Marshal(bson.M{ "Word": "beach", "Synonyms": bson.A{"coast", "shore", "waterfront"}, }) if err != nil { panic(err) } var res struct { Word string Synonyms bson.Raw // Don't parse the whole list, we just want to count the elements. } err = bson.Unmarshal(b, &res) if err != nil { panic(err) } elems, err := res.Synonyms.Elements() if err != nil { panic(err) } fmt.Printf("%s, synonyms count: %d\n", res.Word, len(elems)) }
Output: beach, synonyms count: 3
func NewFromIOReader
deprecated
func ReadDocument ¶
ReadDocument reads a BSON document from the io.Reader and returns it as a bson.Raw. If the reader contains multiple BSON documents, only the first document is read.
func (Raw) Elements ¶
func (r Raw) Elements() ([]RawElement, error)
Elements returns this document as a slice of elements. The returned slice will contain valid elements. If the document is not valid, the elements up to the invalid point will be returned along with an error.
func (Raw) Index ¶
func (r Raw) Index(index uint) RawElement
Index searches for and retrieves the element at the given index. This method will panic if the document is invalid or if the index is out of bounds.
func (Raw) IndexErr ¶
func (r Raw) IndexErr(index uint) (RawElement, error)
IndexErr searches for and retrieves the element at the given index.
func (Raw) Lookup ¶
Lookup search the document, potentially recursively, for the given key. If there are multiple keys provided, this method will recurse down, as long as the top and intermediate nodes are either documents or arrays.If an error occurs or if the value doesn't exist, an empty RawValue is returned.
func (Raw) LookupErr ¶
LookupErr searches the document and potentially subdocuments or arrays for the provided key. Each key provided to this method represents a layer of depth.
func (Raw) Validate ¶
Validate validates the document. This method only validates the first document in the slice, to validate other documents, the slice must be resliced.
Example ¶
rdr := make(Raw, 500) rdr[250], rdr[251], rdr[252], rdr[253], rdr[254] = '\x05', '\x00', '\x00', '\x00', '\x00' err := rdr[250:].Validate() fmt.Println(err)
Output: <nil>
type RawElement ¶
type RawElement []byte
RawElement is a raw encoded BSON document or array element.
func (RawElement) DebugString ¶
func (re RawElement) DebugString() string
DebugString outputs a human readable version of RawElement. It will attempt to stringify the valid components of the element even if the entire element is not valid.
func (RawElement) Key ¶
func (re RawElement) Key() string
Key returns the key for this element. If the element is not valid, this method returns an empty string. If knowing if the element is valid is important, use KeyErr.
func (RawElement) KeyErr ¶
func (re RawElement) KeyErr() (string, error)
KeyErr returns the key for this element, returning an error if the element is not valid.
func (RawElement) String ¶
func (re RawElement) String() string
String returns the BSON element encoded as Extended JSON.
func (RawElement) Validate ¶
func (re RawElement) Validate() error
Validate ensures re is a valid BSON element.
func (RawElement) Value ¶
func (re RawElement) Value() RawValue
Value returns the value of this element. If the element is not valid, this method returns an empty Value. If knowing if the element is valid is important, use ValueErr.
func (RawElement) ValueErr ¶
func (re RawElement) ValueErr() (RawValue, error)
ValueErr returns the value for this element, returning an error if the element is not valid.
type RawValue ¶
RawValue is a raw encoded BSON value. It can be used to delay BSON value decoding or precompute BSON encoded value. Type is the BSON type of the value and Value is the raw encoded BSON value.
A RawValue must be an individual BSON value. Use the Raw type for full BSON documents.
Example (Marshal) ¶
This example uses RawValue to add a precomputed BSON string value during marshal.
package main import ( "fmt" "time" "go.mongodb.org/mongo-driver/bson" ) func main() { t, val, err := bson.MarshalValue("Precomputed message!") if err != nil { panic(err) } precomputed := bson.RawValue{ Type: t, Value: val, } msg := struct { Message bson.RawValue Time time.Time }{ Message: precomputed, Time: time.Unix(1675282389, 0), } b, err := bson.Marshal(msg) if err != nil { panic(err) } // Print the Extended JSON by converting BSON to bson.Raw. fmt.Println(bson.Raw(b).String()) }
Output: {"message": "Precomputed message!","time": {"$date":{"$numberLong":"1675282389000"}}}
Example (Unmarshal) ¶
This example uses RawValue to delay parsing a value in a BSON message.
package main import ( "fmt" "time" "go.mongodb.org/mongo-driver/bson" ) func main() { b1, err := bson.Marshal(bson.M{ "Format": "UNIX", "Timestamp": 1675282389, }) if err != nil { panic(err) } b2, err := bson.Marshal(bson.M{ "Format": "RFC3339", "Timestamp": time.Unix(1675282389, 0).Format(time.RFC3339), }) if err != nil { panic(err) } for _, b := range [][]byte{b1, b2} { var res struct { Format string Timestamp bson.RawValue // Delay parsing until we know the timestamp format. } err = bson.Unmarshal(b, &res) if err != nil { panic(err) } var t time.Time switch res.Format { case "UNIX": t = time.Unix(res.Timestamp.AsInt64(), 0) case "RFC3339": t, err = time.Parse(time.RFC3339, res.Timestamp.StringValue()) if err != nil { panic(err) } } fmt.Println(res.Format, t.Unix()) } }
Output: UNIX 1675282389 RFC3339 1675282389
func (RawValue) Array ¶
Array returns the BSON array the Value represents as an Array. It panics if the value is a BSON type other than array.
func (RawValue) ArrayOK ¶
ArrayOK is the same as Array, except it returns a boolean instead of panicking.
func (RawValue) AsInt32
deprecated
func (RawValue) AsInt32OK
deprecated
func (RawValue) AsInt64 ¶
AsInt64 returns a BSON number as an int64. If the BSON type is not a numeric one, this method will panic.
func (RawValue) AsInt64OK ¶
AsInt64OK is the same as AsInt64, except that it returns a boolean instead of panicking.
func (RawValue) Binary ¶
Binary returns the BSON binary value the Value represents. It panics if the value is a BSON type other than binary.
func (RawValue) BinaryOK ¶
BinaryOK is the same as Binary, except it returns a boolean instead of panicking.
func (RawValue) Boolean ¶
Boolean returns the boolean value the Value represents. It panics if the value is a BSON type other than boolean.
func (RawValue) BooleanOK ¶
BooleanOK is the same as Boolean, except it returns a boolean instead of panicking.
func (RawValue) CodeWithScope ¶
CodeWithScope returns the BSON JavaScript code with scope the Value represents. It panics if the value is a BSON type other than JavaScript code with scope.
func (RawValue) CodeWithScopeOK ¶
CodeWithScopeOK is the same as CodeWithScope, except that it returns a boolean instead of panicking.
func (RawValue) DBPointer ¶
DBPointer returns the BSON dbpointer value the Value represents. It panics if the value is a BSON type other than DBPointer.
func (RawValue) DBPointerOK ¶
DBPointerOK is the same as DBPoitner, except that it returns a boolean instead of panicking.
func (RawValue) DateTime ¶
DateTime returns the BSON datetime value the Value represents as a unix timestamp. It panics if the value is a BSON type other than datetime.
func (RawValue) DateTimeOK ¶
DateTimeOK is the same as DateTime, except it returns a boolean instead of panicking.
func (RawValue) DebugString ¶
DebugString outputs a human readable version of Document. It will attempt to stringify the valid components of the document even if the entire document is not valid.
func (RawValue) Decimal128 ¶
func (rv RawValue) Decimal128() primitive.Decimal128
Decimal128 returns the decimal the Value represents. It panics if the value is a BSON type other than decimal.
func (RawValue) Decimal128OK ¶
func (rv RawValue) Decimal128OK() (primitive.Decimal128, bool)
Decimal128OK is the same as Decimal128, except that it returns a boolean instead of panicking.
func (RawValue) Document ¶
Document returns the BSON document the Value represents as a Document. It panics if the value is a BSON type other than document.
func (RawValue) DocumentOK ¶
DocumentOK is the same as Document, except it returns a boolean instead of panicking.
func (RawValue) Double ¶
Double returns the float64 value for this element. It panics if e's BSON type is not bsontype.Double.
func (RawValue) DoubleOK ¶
DoubleOK is the same as Double, but returns a boolean instead of panicking.
func (RawValue) Int32 ¶
Int32 returns the int32 the Value represents. It panics if the value is a BSON type other than int32.
func (RawValue) Int32OK ¶
Int32OK is the same as Int32, except that it returns a boolean instead of panicking.
func (RawValue) Int64 ¶
Int64 returns the int64 the Value represents. It panics if the value is a BSON type other than int64.
func (RawValue) Int64OK ¶
Int64OK is the same as Int64, except that it returns a boolean instead of panicking.
func (RawValue) IsZero ¶
IsZero reports whether the RawValue is zero, i.e. no data is present on the RawValue. It returns true if Type is 0 and Value is empty or nil.
func (RawValue) JavaScript ¶
JavaScript returns the BSON JavaScript code value the Value represents. It panics if the value is a BSON type other than JavaScript code.
func (RawValue) JavaScriptOK ¶
JavaScriptOK is the same as Javascript, excepti that it returns a boolean instead of panicking.
func (RawValue) ObjectID ¶
ObjectID returns the BSON objectid value the Value represents. It panics if the value is a BSON type other than objectid.
func (RawValue) ObjectIDOK ¶
ObjectIDOK is the same as ObjectID, except it returns a boolean instead of panicking.
func (RawValue) Regex ¶
Regex returns the BSON regex value the Value represents. It panics if the value is a BSON type other than regex.
func (RawValue) RegexOK ¶
RegexOK is the same as Regex, except it returns a boolean instead of panicking.
func (RawValue) String ¶
String implements the fmt.String interface. This method will return values in extended JSON format. If the value is not valid, this returns an empty string
func (RawValue) StringValue ¶
StringValue returns the string value for this element. It panics if e's BSON type is not bsontype.String.
NOTE: This method is called StringValue to avoid a collision with the String method which implements the fmt.Stringer interface.
func (RawValue) StringValueOK ¶
StringValueOK is the same as StringValue, but returns a boolean instead of panicking.
func (RawValue) Symbol ¶
Symbol returns the BSON symbol value the Value represents. It panics if the value is a BSON type other than symbol.
func (RawValue) SymbolOK ¶
SymbolOK is the same as Symbol, excepti that it returns a boolean instead of panicking.
func (RawValue) Time ¶
Time returns the BSON datetime value the Value represents. It panics if the value is a BSON type other than datetime.
func (RawValue) TimeOK ¶
TimeOK is the same as Time, except it returns a boolean instead of panicking.
func (RawValue) Timestamp ¶
Timestamp returns the BSON timestamp value the Value represents. It panics if the value is a BSON type other than timestamp.
func (RawValue) TimestampOK ¶
TimestampOK is the same as Timestamp, except that it returns a boolean instead of panicking.
func (RawValue) Unmarshal ¶
Unmarshal deserializes BSON into the provided val. If RawValue cannot be unmarshaled into val, an error is returned. This method will use the registry used to create the RawValue, if the RawValue was created from partial BSON processing, or it will use the default registry. Users wishing to specify the registry to use should use UnmarshalWithRegistry.
func (RawValue) UnmarshalWithContext ¶
func (rv RawValue) UnmarshalWithContext(dc *bsoncodec.DecodeContext, val interface{}) error
UnmarshalWithContext performs the same unmarshalling as Unmarshal but uses the provided DecodeContext instead of the one attached or the default registry.
func (RawValue) UnmarshalWithRegistry ¶
UnmarshalWithRegistry performs the same unmarshalling as Unmarshal but uses the provided registry instead of the one attached or the default registry.
type Unmarshaler ¶
Unmarshaler is the interface implemented by types that can unmarshal a BSON document representation of themselves. The input can be assumed to be a valid encoding of a BSON document. UnmarshalBSON must copy the JSON data if it wishes to retain the data after returning.
Unmarshaler is only used to unmarshal full BSON documents. To create custom BSON unmarshaling behavior for individual values in a BSON document, implement the ValueUnmarshaler interface instead.
type ValueMarshaler ¶
ValueMarshaler is the interface implemented by types that can marshal themselves into a valid BSON value. The format of the returned bytes must match the returned type.
Implementations of ValueMarshaler must return an individual BSON value. To create custom BSON marshaling behavior for an entire BSON document, implement the Marshaler interface instead.
type ValueUnmarshaler ¶
ValueUnmarshaler is the interface implemented by types that can unmarshal a BSON value representation of themselves. The input can be assumed to be a valid encoding of a BSON value. UnmarshalBSONValue must copy the BSON value bytes if it wishes to retain the data after returning.
ValueUnmarshaler is only used to unmarshal individual values in a BSON document. To create custom BSON unmarshaling behavior for an entire BSON document, implement the Unmarshaler interface instead.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package bsoncodec provides a system for encoding values to BSON representations and decoding values from BSON representations.
|
Package bsoncodec provides a system for encoding values to BSON representations and decoding values from BSON representations. |
Package bsonoptions defines the optional configurations for the BSON codecs.
|
Package bsonoptions defines the optional configurations for the BSON codecs. |
Package bsonrw contains abstractions for reading and writing BSON and BSON like types from sources.
|
Package bsonrw contains abstractions for reading and writing BSON and BSON like types from sources. |
bsonrwtest
Package bsonrwtest provides utilities for testing the "bson/bsonrw" package.
|
Package bsonrwtest provides utilities for testing the "bson/bsonrw" package. |
Package bsontype is a utility package that contains types for each BSON type and the a stringifier for the Type to enable easier debugging when working with BSON.
|
Package bsontype is a utility package that contains types for each BSON type and the a stringifier for the Type to enable easier debugging when working with BSON. |
Package mgocompat provides Registry, a BSON registry compatible with globalsign/mgo's BSON, with some remaining differences.
|
Package mgocompat provides Registry, a BSON registry compatible with globalsign/mgo's BSON, with some remaining differences. |
Package primitive contains types similar to Go primitives for BSON types that do not have direct Go primitive representations.
|
Package primitive contains types similar to Go primitives for BSON types that do not have direct Go primitive representations. |