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
- Variables
- func BSONElementSize(kind byte, offset int, buffer []byte) (int, error)
- func IsObjectIdHex(s string) bool
- func JSONTagFallbackState() bool
- func Marshal(in interface{}) (out []byte, err error)
- func MarshalBuffer(in interface{}, buf []byte) (out []byte, err error)
- func MarshalJSON(value interface{}) ([]byte, error)
- func Now() time.Time
- func RespectNilValuesState() bool
- func SetJSONTagFallback(state bool)
- func SetRespectNilValues(state bool)
- func Unmarshal(in []byte, out interface{}) (err error)
- func UnmarshalJSON(data []byte, value interface{}) error
- type Binary
- type D
- type DBPointer
- type Decimal128
- type Decoder
- type DocElem
- type Encoder
- type ErrInvalidDocumentSize
- type Getter
- type JavaScript
- type M
- type MongoTimestamp
- type ObjectId
- func (id ObjectId) Counter() int32
- func (id ObjectId) Hex() string
- func (id ObjectId) Machine() []byte
- func (id ObjectId) MarshalJSON() ([]byte, error)
- func (id ObjectId) MarshalText() ([]byte, error)
- func (id ObjectId) Pid() uint16
- func (id ObjectId) String() string
- func (id ObjectId) Time() time.Time
- func (id *ObjectId) UnmarshalJSON(data []byte) error
- func (id *ObjectId) UnmarshalText(data []byte) error
- func (id ObjectId) Valid() bool
- type Raw
- type RawD
- type RawDocElem
- type RegEx
- type Setter
- type Symbol
- type TypeError
Examples ¶
Constants ¶
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.
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 https://docs.mongodb.com/manual/reference/limits/). MaxDocumentSize = 16777216 )
Variables ¶
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.
var MaxKey = orderKey(1<<63 - 1)
MaxKey is a special value that compares higher than all other possible BSON values in a MongoDB database.
var MinKey = orderKey(-1 << 63)
MinKey is a special value that compares lower than all other possible BSON values in a MongoDB database.
var Undefined undefined
Undefined represents the undefined BSON value.
Functions ¶
func IsObjectIdHex ¶
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 ¶
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 MarshalBuffer ¶
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 ¶
MarshalJSON marshals a JSON value that may hold non-standard syntax as defined in BSON's extended JSON specification.
func Now ¶
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 ¶
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 ¶
UnmarshalJSON unmarshals a JSON value that may hold non-standard syntax as defined in BSON's extended JSON specification.
Types ¶
type Binary ¶
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.
type DBPointer ¶
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 ¶
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.
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 ¶
NewEncoder returns a new Encoder that writes to target.
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).
Example ¶
var counter uint32 = 1 var t time.Time for i := 1; i <= 3; i++ { if c := time.Now(); t.Unix() == c.Unix() { counter++ } 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) }
Output:
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.
http://www.mongodb.org/display/DOCS/Object+Ids
func NewObjectIdWithTime ¶
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 ¶
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 ¶
Counter returns the incrementing value part of the id. It's a runtime error to call this method with an invalid id.
func (ObjectId) Machine ¶
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 ¶
MarshalJSON turns a bson.ObjectId into a json.Marshaller.
func (ObjectId) MarshalText ¶
MarshalText turns bson.ObjectId into an encoding.TextMarshaler.
func (ObjectId) Pid ¶
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 ¶
String returns a hex string representation of the id. Example: ObjectIdHex("4d88e15b60f486e428412dc9").
func (ObjectId) 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 ¶
UnmarshalJSON turns *bson.ObjectId into a json.Unmarshaller.
func (*ObjectId) UnmarshalText ¶
UnmarshalText turns *bson.ObjectId into an encoding.TextUnmarshaler.
type Raw ¶
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
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 ¶
RawDocElem elements of RawD type.
type RegEx ¶
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 ¶
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) }