v0.0.0-...-eeefdec Latest Latest

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2018 License: BSD-2-Clause, BSD-2-Clause Imports: 22 Imported by: 2,081



An Implementation of BSON for Go

Package bson is an implementation of the BSON specification for Go.

While the BSON package implements the BSON spec as faithfully as possible, there is some MongoDB specific behaviour (such as map keys $in, $all, etc) in the bson package. The priority is for backwards compatibility for the mgo driver, though fixes for obviously buggy behaviour is welcome (and features, etc behind feature flags).



Package bson is an implementation of the BSON specification for Go:

It was created as part of the mgo MongoDB driver for Go, but is standalone and may be used on its own without the driver.




View Source
const (
	ElementFloat64                byte = 0x01
	ElementString                 byte = 0x02
	ElementDocument               byte = 0x03
	ElementArray                  byte = 0x04
	ElementBinary                 byte = 0x05
	Element06                     byte = 0x06
	ElementObjectId               byte = 0x07
	ElementBool                   byte = 0x08
	ElementDatetime               byte = 0x09
	ElementNil                    byte = 0x0A
	ElementRegEx                  byte = 0x0B
	ElementDBPointer              byte = 0x0C
	ElementJavaScriptWithoutScope byte = 0x0D
	ElementSymbol                 byte = 0x0E
	ElementJavaScriptWithScope    byte = 0x0F
	ElementInt32                  byte = 0x10
	ElementTimestamp              byte = 0x11
	ElementInt64                  byte = 0x12
	ElementDecimal128             byte = 0x13
	ElementMinKey                 byte = 0xFF
	ElementMaxKey                 byte = 0x7F

	BinaryGeneric     byte = 0x00
	BinaryFunction    byte = 0x01
	BinaryBinaryOld   byte = 0x02
	BinaryUUIDOld     byte = 0x03
	BinaryUUID        byte = 0x04
	BinaryMD5         byte = 0x05
	BinaryUserDefined byte = 0x80

Element types constants from BSON specification.

View Source
const (
	// MinDocumentSize is the size of the smallest possible valid BSON document:
	// an int32 size header + 0x00 (end of document).
	MinDocumentSize = 5

	// MaxDocumentSize is the largest possible size for a BSON document allowed by MongoDB,
	// that is, 16 MiB (see
	MaxDocumentSize = 16777216


View Source
var ErrSetZero = errors.New("set to zero")

ErrSetZero may be returned from a SetBSON method to have the value set to its respective zero value. When used in pointer values, this will set the field to nil rather than to the pre-allocated value.

View Source
var MaxKey = orderKey(1<<63 - 1)

MaxKey is a special value that compares higher than all other possible BSON values in a MongoDB database.

View Source
var MinKey = orderKey(-1 << 63)

MinKey is a special value that compares lower than all other possible BSON values in a MongoDB database.

View Source
var Undefined undefined

Undefined represents the undefined BSON value.


func BSONElementSize

func BSONElementSize(kind byte, offset int, buffer []byte) (int, error)

func IsObjectIdHex

func IsObjectIdHex(s string) bool

IsObjectIdHex returns whether s is a valid hex representation of an ObjectId. See the ObjectIdHex function.

func JSONTagFallbackState

func JSONTagFallbackState() bool

JSONTagFallbackState returns the current status of the JSON tag fallback compatability option. See SetJSONTagFallback for more information.

func Marshal

func Marshal(in interface{}) (out []byte, err error)

Marshal serializes the in value, which may be a map or a struct value. In the case of struct values, only exported fields will be serialized, and the order of serialized fields will match that of the struct itself. The lowercased field name is used as the key for each exported field, but this behavior may be changed using the respective field tag. The tag may also contain flags to tweak the marshalling behavior for the field. The tag formats accepted are:


`(...) bson:"[<key>][,<flag1>[,<flag2>]]" (...)`

The following flags are currently supported:

omitempty  Only include the field if it's not set to the zero
           value for the type or to empty slices or maps.

minsize    Marshal an int64 value as an int32, if that's feasible
           while preserving the numeric value.

inline     Inline the field, which must be a struct or a map,
           causing all of its fields or keys to be processed as if
           they were part of the outer struct. For maps, keys must
           not conflict with the bson keys of other struct fields.

Some examples:

type T struct {
    A bool
    B int    "myb"
    C string "myc,omitempty"
    D string `bson:",omitempty" json:"jsonkey"`
    E int64  ",minsize"
    F int64  "myf,omitempty,minsize"

func MarshalBuffer

func MarshalBuffer(in interface{}, buf []byte) (out []byte, err error)

MarshalBuffer behaves the same way as Marshal, except that instead of allocating a new byte slice it tries to use the received byte slice and only allocates more memory if necessary to fit the marshaled value.

func MarshalJSON

func MarshalJSON(value interface{}) ([]byte, error)

MarshalJSON marshals a JSON value that may hold non-standard syntax as defined in BSON's extended JSON specification.

func Now

func Now() time.Time

Now returns the current time with millisecond precision. MongoDB stores timestamps with the same precision, so a Time returned from this method will not change after a roundtrip to the database. That's the only reason why this function exists. Using the time.Now function also works fine otherwise.

func RespectNilValuesState

func RespectNilValuesState() bool

RespectNilValuesState returns the current status of the JSON nil slices and maps fallback compatibility option. See SetRespectNilValues for more information.

func SetJSONTagFallback

func SetJSONTagFallback(state bool)

SetJSONTagFallback enables or disables the JSON-tag fallback for structure tagging. When this is enabled, structures without BSON tags on a field will fall-back to using the JSON tag (if present).

func SetRespectNilValues

func SetRespectNilValues(state bool)

SetRespectNilValues enables or disables serializing nil slices or maps to `null` values. In other words it enables `encoding/json` compatible behaviour.

func Unmarshal

func Unmarshal(in []byte, out interface{}) (err error)

Unmarshal deserializes data from in into the out value. The out value must be a map, a pointer to a struct, or a pointer to a bson.D value. In the case of struct values, only exported fields will be deserialized. The lowercased field name is used as the key for each exported field, but this behavior may be changed using the respective field tag. The tag may also contain flags to tweak the marshalling behavior for the field. The tag formats accepted are:


`(...) bson:"[<key>][,<flag1>[,<flag2>]]" (...)`

The following flags are currently supported during unmarshal (see the Marshal method for other flags):

inline     Inline the field, which must be a struct or a map.
           Inlined structs are handled as if its fields were part
           of the outer struct. An inlined map causes keys that do
           not match any other struct field to be inserted in the
           map rather than being discarded as usual.

The target field or element types of out may not necessarily match the BSON values of the provided data. The following conversions are made automatically:

  • Numeric types are converted if at least the integer part of the value would be preserved correctly
  • Bools are converted to numeric types as 1 or 0
  • Numeric types are converted to bools as true if not 0 or false otherwise
  • Binary and string BSON data is converted to a string, array or byte slice

If the value would not fit the type and cannot be converted, it's silently skipped.

Pointer values are initialized when necessary.

func UnmarshalJSON

func UnmarshalJSON(data []byte, value interface{}) error

UnmarshalJSON unmarshals a JSON value that may hold non-standard syntax as defined in BSON's extended JSON specification.


type Binary

type Binary struct {
	Kind byte
	Data []byte

Binary is a representation for non-standard binary values. Any kind should work, but the following are known as of this writing:

0x00 - Generic. This is decoded as []byte(data), not Binary{0x00, data}.
0x01 - Function (!?)
0x02 - Obsolete generic.
0x03 - UUID
0x05 - MD5
0x80 - User defined.

type D

type D []DocElem

D represents a BSON document containing ordered elements. For example:

bson.D{{"a", 1}, {"b", true}}

In some situations, such as when creating indexes for MongoDB, the order in which the elements are defined is important. If the order is not important, using a map is generally more comfortable. See bson.M and bson.RawD.

func (D) Map

func (d D) Map() (m M)

Map returns a map out of the ordered element name/value pairs in d.

type DBPointer

type DBPointer struct {
	Namespace string
	Id        ObjectId

DBPointer refers to a document id in a namespace.

This type is deprecated in the BSON specification and should not be used except for backwards compatibility with ancient applications.

type Decimal128

type Decimal128 struct {
	// contains filtered or unexported fields

Decimal128 holds decimal128 BSON values.

func ParseDecimal128

func ParseDecimal128(s string) (Decimal128, error)

ParseDecimal128 parse a string and return the corresponding value as a decimal128

func (Decimal128) String

func (d Decimal128) String() string

type Decoder

type Decoder struct {
	// contains filtered or unexported fields

A Decoder reads and decodes BSON values from an input stream.

func NewDecoder

func NewDecoder(source io.Reader) *Decoder

NewDecoder returns a new Decoder that reads from source. It does not add any extra buffering, and may not read data from source beyond the BSON values requested.

func (*Decoder) Decode

func (dec *Decoder) Decode(v interface{}) (err error)

Decode reads the next BSON-encoded value from its input and stores it in the value pointed to by v. See the documentation for Unmarshal for details about the conversion of BSON into a Go value.

type DocElem

type DocElem struct {
	Name  string
	Value interface{}

DocElem is an element of the bson.D document representation.

type Encoder

type Encoder struct {
	// contains filtered or unexported fields

An Encoder encodes and writes BSON values to an output stream.

func NewEncoder

func NewEncoder(target io.Writer) *Encoder

NewEncoder returns a new Encoder that writes to target.

func (*Encoder) Encode

func (enc *Encoder) Encode(v interface{}) error

Encode encodes v to BSON, and if successful writes it to the Encoder's output stream. See the documentation for Marshal for details about the conversion of Go values to BSON.

type ErrInvalidDocumentSize

type ErrInvalidDocumentSize struct {
	DocumentSize int32

ErrInvalidDocumentSize is an error returned when a BSON document's header contains a size smaller than MinDocumentSize or greater than MaxDocumentSize.

func (ErrInvalidDocumentSize) Error

func (e ErrInvalidDocumentSize) Error() string

type Getter

type Getter interface {
	GetBSON() (interface{}, error)

Getter interface: a value implementing the bson.Getter interface will have its GetBSON method called when the given value has to be marshalled, and the result of this method will be marshaled in place of the actual object.

If GetBSON returns return a non-nil error, the marshalling procedure will stop and error out with the provided value.

type JavaScript

type JavaScript struct {
	Code  string
	Scope interface{}

JavaScript is a type that holds JavaScript code. If Scope is non-nil, it will be marshaled as a mapping from identifiers to values that may be used when evaluating the provided Code.

type M

type M map[string]interface{}

M is a convenient alias for a map[string]interface{} map, useful for dealing with BSON in a native way. For instance:

bson.M{"a": 1, "b": true}

There's no special handling for this type in addition to what's done anyway for an equivalent map type. Elements in the map will be dumped in an undefined ordered. See also the bson.D type for an ordered alternative.

type MongoTimestamp

type MongoTimestamp int64

MongoTimestamp is a special internal type used by MongoDB that for some strange reason has its own datatype defined in BSON.

func NewMongoTimestamp

func NewMongoTimestamp(t time.Time, c uint32) (MongoTimestamp, error)

NewMongoTimestamp creates a timestamp using the given date `t` (with second precision) and counter `c` (unique for `t`).

Returns an error if time `t` is not between 1970-01-01T00:00:00Z and 2106-02-07T06:28:15Z (inclusive).

Note that two MongoTimestamps should never have the same (time, counter) combination: the caller must ensure the counter `c` is increased if creating multiple MongoTimestamp values for the same time `t` (ignoring fractions of seconds).

var counter uint32 = 1
var t time.Time

for i := 1; i <= 3; i++ {

	if c := time.Now(); t.Unix() == c.Unix() {
	} else {
		t = c
		counter = 1

	ts, err := bson.NewMongoTimestamp(t, counter)
	if err != nil {
		fmt.Printf("NewMongoTimestamp error: %v", err)
	} else {
		fmt.Printf("NewMongoTimestamp encoded timestamp: %d\n", ts)

	time.Sleep(500 * time.Millisecond)

func (MongoTimestamp) Counter

func (ts MongoTimestamp) Counter() uint32

Counter returns the counter part of ts.

func (MongoTimestamp) Time

func (ts MongoTimestamp) Time() time.Time

Time returns the time part of ts which is stored with second precision.

type ObjectId

type ObjectId string

ObjectId is a unique ID identifying a BSON value. It must be exactly 12 bytes long. MongoDB objects by default have such a property set in their "_id" property.

func NewObjectId

func NewObjectId() ObjectId

NewObjectId returns a new unique ObjectId.

func NewObjectIdWithTime

func NewObjectIdWithTime(t time.Time) ObjectId

NewObjectIdWithTime returns a dummy ObjectId with the timestamp part filled with the provided number of seconds from epoch UTC, and all other parts filled with zeroes. It's not safe to insert a document with an id generated by this method, it is useful only for queries to find documents with ids generated before or after the specified timestamp.

func ObjectIdHex

func ObjectIdHex(s string) ObjectId

ObjectIdHex returns an ObjectId from the provided hex representation. Calling this function with an invalid hex representation will cause a runtime panic. See the IsObjectIdHex function.

func (ObjectId) Counter

func (id ObjectId) Counter() int32

Counter returns the incrementing value part of the id. It's a runtime error to call this method with an invalid id.

func (ObjectId) Hex

func (id ObjectId) Hex() string

Hex returns a hex representation of the ObjectId.

func (ObjectId) Machine

func (id ObjectId) Machine() []byte

Machine returns the 3-byte machine id part of the id. It's a runtime error to call this method with an invalid id.

func (ObjectId) MarshalJSON

func (id ObjectId) MarshalJSON() ([]byte, error)

MarshalJSON turns a bson.ObjectId into a json.Marshaller.

func (ObjectId) MarshalText

func (id ObjectId) MarshalText() ([]byte, error)

MarshalText turns bson.ObjectId into an encoding.TextMarshaler.

func (ObjectId) Pid

func (id ObjectId) Pid() uint16

Pid returns the process id part of the id. It's a runtime error to call this method with an invalid id.

func (ObjectId) String

func (id ObjectId) String() string

String returns a hex string representation of the id. Example: ObjectIdHex("4d88e15b60f486e428412dc9").

func (ObjectId) Time

func (id ObjectId) Time() time.Time

Time returns the timestamp part of the id. It's a runtime error to call this method with an invalid id.

func (*ObjectId) UnmarshalJSON

func (id *ObjectId) UnmarshalJSON(data []byte) error

UnmarshalJSON turns *bson.ObjectId into a json.Unmarshaller.

func (*ObjectId) UnmarshalText

func (id *ObjectId) UnmarshalText(data []byte) error

UnmarshalText turns *bson.ObjectId into an encoding.TextUnmarshaler.

func (ObjectId) Valid

func (id ObjectId) Valid() bool

Valid returns true if id is valid. A valid id must contain exactly 12 bytes.

type Raw

type Raw struct {
	Kind byte
	Data []byte

The Raw type represents raw unprocessed BSON documents and elements. Kind is the kind of element as defined per the BSON specification, and Data is the raw unprocessed data for the respective element. Using this type it is possible to unmarshal or marshal values partially.

Relevant documentation:

func (Raw) Unmarshal

func (raw Raw) Unmarshal(out interface{}) (err error)

Unmarshal deserializes raw into the out value. If the out value type is not compatible with raw, a *bson.TypeError is returned.

See the Unmarshal function documentation for more details on the unmarshalling process.

type RawD

type RawD []RawDocElem

RawD represents a BSON document containing raw unprocessed elements. This low-level representation may be useful when lazily processing documents of uncertain content, or when manipulating the raw content documents in general.

type RawDocElem

type RawDocElem struct {
	Name  string
	Value Raw

RawDocElem elements of RawD type.

type RegEx

type RegEx struct {
	Pattern string
	Options string

RegEx represents a regular expression. The Options field may contain individual characters defining the way in which the pattern should be applied, and must be sorted. Valid options as of this writing are 'i' for case insensitive matching, 'm' for multi-line matching, 'x' for verbose mode, 'l' to make \w, \W, and similar be locale-dependent, 's' for dot-all mode (a '.' matches everything), and 'u' to make \w, \W, and similar match unicode. The value of the Options parameter is not verified before being marshaled into the BSON format.

type Setter

type Setter interface {
	SetBSON(raw Raw) error

Setter interface: a value implementing the bson.Setter interface will receive the BSON value via the SetBSON method during unmarshaling, and the object itself will not be changed as usual.

If setting the value works, the method should return nil or alternatively bson.ErrSetZero to set the respective field to its zero value (nil for pointer types). If SetBSON returns a value of type bson.TypeError, the BSON value will be omitted from a map or slice being decoded and the unmarshalling will continue. If it returns any other non-nil error, the unmarshalling procedure will stop and error out with the provided value.

This interface is generally useful in pointer receivers, since the method will want to change the receiver. A type field that implements the Setter interface doesn't have to be a pointer, though.

Unlike the usual behavior, unmarshalling onto a value that implements a Setter interface will NOT reset the value to its zero state. This allows the value to decide by itself how to be unmarshalled.

For example:

type MyString string

func (s *MyString) SetBSON(raw bson.Raw) error {
    return raw.Unmarshal(s)

type Symbol

type Symbol string

The Symbol type is similar to a string and is used in languages with a distinct symbol type.

type TypeError

type TypeError struct {
	Type reflect.Type
	Kind byte

TypeError store details for type error occuring during unmarshaling

func (*TypeError) Error

func (e *TypeError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL