bson

package
v2.0.0-...-a6b53ec Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2019 License: BSD-2-Clause, BSD-2-Clause Imports: 19 Imported by: 12,490

Documentation

Overview

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

http://bsonspec.org

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.

Index

Constants

This section is empty.

Variables

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 SetZero = errors.New("set to zero")

SetZero 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 Undefined undefined

Undefined represents the undefined BSON value.

Functions

func IsObjectIdHex

func IsObjectIdHex(s string) bool

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

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:

"[<key>][,<flag1>[,<flag2>]]"

`(...) 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 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 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:

"[<key>][,<flag1>[,<flag2>]]"

`(...) 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.

Types

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)

func (Decimal128) String

func (d Decimal128) String() string

type DocElem

type DocElem struct {
	Name  string
	Value interface{}
}

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

type Getter

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

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.

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.

http://www.mongodb.org/display/DOCS/Object+IDs

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:

http://bsonspec.org/#/specification

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
}

See the 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
}

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.SetZero 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
}

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