MongoDB  2.7.0
Classes | Public Types | Public Member Functions | Static Public Member Functions | Friends | List of all members
mongo::BSONObj Class Reference

C++ representation of a "BSON" object – that is, an extended JSON-style object in a binary representation. More...

#include <bsonobj.h>

Inheritance diagram for mongo::BSONObj:
mongo::BSONArray

Classes

class  Holder
 
struct  SorterDeserializeSettings
 members for Sorter More...
 

Public Types

enum  { maxToStringRecursionDepth = 100 }
 Readable representation of a BSON object in an extended JSON-style notation. More...
 
enum  MatchType {
  Equality = 0, LT = 0x1, LTE = 0x3, GTE = 0x6,
  GT = 0x4, opIN = 0x8, NE = 0x9, opSIZE = 0x0A,
  opALL = 0x0B, NIN = 0x0C, opEXISTS = 0x0D, opMOD = 0x0E,
  opTYPE = 0x0F, opREGEX = 0x10, opOPTIONS = 0x11, opELEM_MATCH = 0x12,
  opNEAR = 0x13, opWITHIN = 0x14, opMAX_DISTANCE = 0x15, opGEO_INTERSECTS = 0x16
}
 
typedef BSONObjIterator iterator
 

Public Member Functions

 BSONObj (const char *msgdata)
 Construct a BSONObj from data in the proper format. More...
 
 BSONObj (Holder *holder)
 
 BSONObj ()
 Construct an empty BSONObj – that is, {}. More...
 
bool isOwned () const
 A BSONObj can use a buffer it "owns" or one it does not. More...
 
BSONObj getOwned () const
 assure the data buffer is under the control of this BSONObj and not a remote buffer More...
 
BSONObj copy () const
 
std::string toString (bool isArray=false, bool full=false) const
 
void toString (StringBuilder &s, bool isArray=false, bool full=false, int depth=0) const
 
std::string jsonString (JsonStringFormat format=Strict, int pretty=0) const
 Properly formatted JSON string. More...
 
int addFields (BSONObj &from, std::set< std::string > &fields)
 note: addFields always adds _id even if not specified
 
BSONObj removeField (const StringData &name) const
 remove specified field and return a new object with the remaining fields. More...
 
int nFields () const
 returns # of top level fields in the object note: iterates to count the fields
 
int getFieldNames (std::set< std::string > &fields) const
 adds the field names to the fields set. More...
 
BSONElement getFieldDotted (const StringData &name) const
 
void getFieldsDotted (const StringData &name, BSONElementSet &ret, bool expandLastArray=true) const
 Like getFieldDotted(), but expands arrays and returns all matching objects. More...
 
void getFieldsDotted (const StringData &name, BSONElementMSet &ret, bool expandLastArray=true) const
 
BSONElement getFieldDottedOrArray (const char *&name) const
 Like getFieldDotted(), but returns first array encountered while traversing the dotted fields of name. More...
 
BSONElement getField (const StringData &name) const
 Get the field of the specified name. More...
 
void getFields (unsigned n, const char **fieldNames, BSONElement *fields) const
 Get several fields at once. More...
 
BSONElement operator[] (const StringData &field) const
 Get the field of the specified name. More...
 
BSONElement operator[] (int field) const
 
bool hasField (const StringData &name) const
 
bool hasElement (const StringData &name) const
 
const char * getStringField (const StringData &name) const
 
BSONObj getObjectField (const StringData &name) const
 
int getIntField (const StringData &name) const
 
bool getBoolField (const StringData &name) const
 
BSONObj extractFieldsUnDotted (const BSONObj &pattern) const
 
BSONObj extractFields (const BSONObj &pattern, bool fillWithNull=false) const
 extract items from object which match a pattern object. More...
 
BSONObj filterFieldsUndotted (const BSONObj &filter, bool inFilter) const
 
BSONElement getFieldUsingIndexNames (const StringData &fieldName, const BSONObj &indexKey) const
 
bool couldBeArray () const
 arrays are bson objects with numeric and increasing field names More...
 
const char * objdata () const
 
int objsize () const
 
bool isValid () const
 performs a cursory check on the object's size only. More...
 
bool okForStorage () const
 
bool okForStorageAsRoot () const
 Same as above with the following extra restrictions Not valid if: More...
 
Status storageValidEmbedded (const bool deep=true) const
 Validates that this can be stored as an embedded document See details above in okForStorage. More...
 
Status storageValid (const bool deep=true) const
 Validates that this can be stored as a document (in a collection) See details above in okForStorageAsRoot. More...
 
bool isEmpty () const
 
void dump () const
 
std::string hexDump () const
 Alternative output format.
 
int woCompare (const BSONObj &r, const Ordering &o, bool considerFieldName=true) const
 wo='well ordered'. More...
 
int woCompare (const BSONObj &r, const BSONObj &ordering=BSONObj(), bool considerFieldName=true) const
 wo='well ordered'. More...
 
bool operator< (const BSONObj &other) const
 
bool operator<= (const BSONObj &other) const
 
bool operator> (const BSONObj &other) const
 
bool operator>= (const BSONObj &other) const
 
int woSortOrder (const BSONObj &r, const BSONObj &sortKey, bool useDotted=false) const
 
bool equal (const BSONObj &r) const
 
bool isPrefixOf (const BSONObj &otherObj) const
 
bool isFieldNamePrefixOf (const BSONObj &otherObj) const
 
bool binaryEqual (const BSONObj &r) const
 This is "shallow equality" – ints and doubles won't match. More...
 
BSONElement firstElement () const
 
const char * firstElementFieldName () const
 faster than firstElement().fieldName() - for the first element we can easily find the fieldname without computing the element size.
 
BSONType firstElementType () const
 
bool getObjectID (BSONElement &e) const
 Get the _id field from the object. More...
 
int hash () const
 
BSONObj clientReadable () const
 
BSONObj replaceFieldNames (const BSONObj &obj) const
 Return new object with the field names replaced by those in the passed object. More...
 
bool valid () const
 true unless corrupt
 
std::string md5 () const
 
bool operator== (const BSONObj &other) const
 
bool operator!= (const BSONObj &other) const
 
void elems (std::vector< BSONElement > &) const
 add all elements of the object to the specified vector
 
void elems (std::list< BSONElement > &) const
 add all elements of the object to the specified list
 
template<class T >
void Vals (std::vector< T > &) const
 add all values of the object to the specified vector. More...
 
template<class T >
void Vals (std::list< T > &) const
 add all values of the object to the specified list. More...
 
template<class T >
void vals (std::vector< T > &) const
 add all values of the object to the specified vector. More...
 
template<class T >
void vals (std::list< T > &) const
 add all values of the object to the specified list. More...
 
BSONObjIterator begin () const
 use something like this: for( BSONObj::iterator i = myObj.begin(); i.more(); ) { BSONElement e = i.next(); ... More...
 
void appendSelfToBufBuilder (BufBuilder &b) const
 
template<typename T >
bool coerceVector (std::vector< T > *out) const
 
 BSONObj (const BSONObj &rO)
 
BSONObjoperator= (const BSONObj &rRHS)
 
void serializeForSorter (BufBuilder &buf) const
 
int memUsageForSorter () const
 

Static Public Member Functions

static BSONObj deserializeForSorter (BufReader &buf, const SorterDeserializeSettings &)
 

Friends

class BSONObjIterator
 

Detailed Description

C++ representation of a "BSON" object – that is, an extended JSON-style object in a binary representation.

See bsonspec.org.

Note that BSONObj's have a smart pointer capability built in – so you can pass them around by value. The reference counts used to implement this do not use locking, so copying and destroying BSONObj's are not thread-safe operations.

BSON object format:

code <unsigned totalsize>=""> {<byte bsontype>=""><cstring fieldname>=""><Data>}* EOO

totalSize includes itself.

Data: Bool: <byte> EOO: nothing follows Undefined: nothing follows OID: an OID object NumberDouble: <double> NumberInt: <int32> String: <unsigned32 strsizewithnull>=""><cstring> Date: <8bytes> Regex: <cstring regex>=""><cstring options>=""> Object: a nested object, leading with its entire size, which terminates with EOO. Array: same as object DBRef: <strlen> <cstring ns>=""> <oid> DBRef: a database reference: basically a collection name plus an Object ID BinData: <int len>=""> <byte subtype>=""> <byte[len] data> Code: a function (not a closure): same format as String. Symbol: a language symbol (say a python symbol). same format as String. Code With Scope: <total size>=""><String><Object>

Member Enumeration Documentation

anonymous enum

Readable representation of a BSON object in an extended JSON-style notation.

This is an abbreviated representation which might be used for logging.

Constructor & Destructor Documentation

mongo::BSONObj::BSONObj ( const char *  msgdata)
inlineexplicit

Construct a BSONObj from data in the proper format.

Use this constructor when something else owns msgdata's buffer

mongo::BSONObj::BSONObj ( )
inline

Construct an empty BSONObj – that is, {}.

Member Function Documentation

BSONObjIterator mongo::BSONObj::begin ( ) const
inline

use something like this: for( BSONObj::iterator i = myObj.begin(); i.more(); ) { BSONElement e = i.next(); ...

}

bool mongo::BSONObj::binaryEqual ( const BSONObj r) const
inline

This is "shallow equality" – ints and doubles won't match.

for a deep equality test use woCompare (which is slower).

NOINLINE_DECL BSONObj mongo::BSONObj::copy ( ) const
inline
Returns
a new full (and owned) copy of the object.
bool mongo::BSONObj::couldBeArray ( ) const

arrays are bson objects with numeric and increasing field names

Returns
true if field names are numeric and increasing
BSONObj mongo::BSONObj::extractFields ( const BSONObj pattern,
bool  fillWithNull = false 
) const

extract items from object which match a pattern object.

e.g., if pattern is { x : 1, y : 1 }, builds an object with x and y elements of this object, if they are present. returns elements with original field names

BSONObj mongo::BSONObj::extractFieldsUnDotted ( const BSONObj pattern) const
Parameters
patterna BSON obj indicating a set of (un-dotted) field names. Element values are ignored.
Returns
a BSON obj constructed by taking the elements of this obj that correspond to the fields in pattern. Field names of the returned object are replaced with the empty string. If field in pattern is missing, it is omitted from the returned object.

Example: if this = {a : 4 , b : 5 , c : 6}) this.extractFieldsUnDotted({a : 1 , c : 1}) -> {"" : 4 , "" : 6 } this.extractFieldsUnDotted({b : "blah"}) -> {"" : 5}

BSONElement mongo::BSONObj::firstElement ( ) const
inline
Returns
first field of the object
bool mongo::BSONObj::getBoolField ( const StringData &  name) const
inline
Returns
false if not present
See Also
BSONElement::trueValue()
BSONElement mongo::BSONObj::getField ( const StringData &  name) const
inline

Get the field of the specified name.

eoo() is true on the returned element if not found.

BSONElement mongo::BSONObj::getFieldDotted ( const StringData &  name) const
inline
Returns
the specified element. element.eoo() will be true if not found.
Parameters
namefield to find. supports dot (".") notation to reach into embedded objects. for example "x.y" means "in the nested object in field x, retrieve field y"
BSONElement mongo::BSONObj::getFieldDottedOrArray ( const char *&  name) const

Like getFieldDotted(), but returns first array encountered while traversing the dotted fields of name.

The name variable is updated to represent field names with respect to the returned element.

int mongo::BSONObj::getFieldNames ( std::set< std::string > &  fields) const

adds the field names to the fields set.

does NOT clear it (appends).

void mongo::BSONObj::getFields ( unsigned  n,
const char **  fieldNames,
BSONElement fields 
) const
inline

Get several fields at once.

This is faster than separate getField() calls as the size of elements iterated can then be calculated only once each.

Parameters
nnumber of fieldNames, and number of elements in the fields array
fieldsif a field is found its element is stored in its corresponding position in this array. if not found the array element is unchanged.
void mongo::BSONObj::getFieldsDotted ( const StringData &  name,
BSONElementSet &  ret,
bool  expandLastArray = true 
) const

Like getFieldDotted(), but expands arrays and returns all matching objects.

Turning off expandLastArray allows you to retrieve nested array objects instead of their contents.

int mongo::BSONObj::getIntField ( const StringData &  name) const
inline
Returns
INT_MIN if not present - does some type conversions
BSONObj mongo::BSONObj::getObjectField ( const StringData &  name) const
inline
Returns
subobject of the given name
bool mongo::BSONObj::getObjectID ( BSONElement e) const
inline

Get the _id field from the object.

For good performance drivers should assure that _id is the first element of the object; however, correct operation is assured regardless.

Returns
true if found
BSONObj mongo::BSONObj::getOwned ( ) const
inline

assure the data buffer is under the control of this BSONObj and not a remote buffer

See Also
isOwned()
const char * mongo::BSONObj::getStringField ( const StringData &  name) const
inline
Returns
"" if DNE or wrong type
bool mongo::BSONObj::hasElement ( const StringData &  name) const
inline
Returns
true if field exists
bool mongo::BSONObj::hasField ( const StringData &  name) const
inline
Returns
true if field exists
int mongo::BSONObj::hash ( ) const
inline
Returns
A hash code for the object
bool mongo::BSONObj::isEmpty ( ) const
inline
Returns
true if object is empty – i.e., {}
bool mongo::BSONObj::isFieldNamePrefixOf ( const BSONObj otherObj) const
Parameters
otherObj
Returns
returns true if the list of field names in 'this' is a prefix of the list of field names in otherObj. Similar to 'isPrefixOf', but ignores the field values and only looks at field names.
bool mongo::BSONObj::isOwned ( ) const
inline

A BSONObj can use a buffer it "owns" or one it does not.

OWNED CASE If the BSONObj owns the buffer, the buffer can be shared among several BSONObj's (by assignment). In this case the buffer is basically implemented as a shared_ptr. Since BSONObj's are typically immutable, this works well.

UNOWNED CASE A BSONObj can also point to BSON data in some other data structure it does not "own" or free later. For example, in a memory mapped file. In this case, it is important the original data stays in scope for as long as the BSONObj is in use. If you think the original data may go out of scope, call BSONObj::getOwned() to promote your BSONObj to having its own copy.

On a BSONObj assignment, if the source is unowned, both the source and dest will have unowned pointers to the original buffer after the assignment.

If you are not sure about ownership but need the buffer to last as long as the BSONObj, call getOwned(). getOwned() is a no-op if the buffer is already owned. If not already owned, a malloc and memcpy will result.

Most ways to create BSONObj's create 'owned' variants. Unowned versions can be created with: (1) specifying true for the ifree parameter in the constructor (2) calling BSONObjBuilder::done(). Use BSONObjBuilder::obj() to get an owned copy (3) retrieving a subobject retrieves an unowned pointer into the parent BSON object

Returns
true if this is in owned mode
bool mongo::BSONObj::isPrefixOf ( const BSONObj otherObj) const
Parameters
otherObj
Returns
true if 'this' is a prefix of otherObj- in other words if otherObj contains the same field names and field vals in the same order as 'this', plus optionally some additional elements.
bool mongo::BSONObj::isValid ( ) const
inline

performs a cursory check on the object's size only.

std::string mongo::BSONObj::jsonString ( JsonStringFormat  format = Strict,
int  pretty = 0 
) const

Properly formatted JSON string.

Parameters
prettyif true we try to add some lf's and indentation
std::string mongo::BSONObj::md5 ( ) const
Returns
an md5 value for this object.
const char* mongo::BSONObj::objdata ( ) const
inline
Returns
the raw data of the object
int mongo::BSONObj::objsize ( ) const
inline
Returns
total size of the BSON object in bytes
bool mongo::BSONObj::okForStorage ( ) const
inline
Returns
ok if it can be stored as a valid embedded doc. Not valid if any field name:
  • contains a "."
  • starts with "$" – unless it is a dbref ($ref/$id/[$db]/...)
bool mongo::BSONObj::okForStorageAsRoot ( ) const
inline

Same as above with the following extra restrictions Not valid if:

  • "_id" field is a – Regex – Array
BSONElement mongo::BSONObj::operator[] ( const StringData &  field) const
inline

Get the field of the specified name.

eoo() is true on the returned element if not found.

BSONObj mongo::BSONObj::removeField ( const StringData &  name) const
inline

remove specified field and return a new object with the remaining fields.

slowish as builds a full new object

BSONObj mongo::BSONObj::replaceFieldNames ( const BSONObj obj) const

Return new object with the field names replaced by those in the passed object.

Status mongo::BSONObj::storageValid ( const bool  deep = true) const
inline

Validates that this can be stored as a document (in a collection) See details above in okForStorageAsRoot.

If 'deep' is true then validation is done to children

If not valid a user readable status message is returned.

Status mongo::BSONObj::storageValidEmbedded ( const bool  deep = true) const
inline

Validates that this can be stored as an embedded document See details above in okForStorage.

If 'deep' is true then validation is done to children

If not valid a user readable status message is returned.

template<class T >
void mongo::BSONObj::Vals ( std::vector< T > &  v) const

add all values of the object to the specified vector.

If type mismatches, exception. this is most useful when the BSONObj is an array, but can be used with non-arrays too in theory.

example: bo sub = y["subobj"].Obj(); std::vector<int> myints; sub.Vals(myints);

template<class T >
void mongo::BSONObj::Vals ( std::list< T > &  v) const

add all values of the object to the specified list.

If type mismatches, exception.

template<class T >
void mongo::BSONObj::vals ( std::vector< T > &  v) const

add all values of the object to the specified vector.

If type mismatches, skip.

template<class T >
void mongo::BSONObj::vals ( std::list< T > &  v) const

add all values of the object to the specified list.

If type mismatches, skip.

int mongo::BSONObj::woCompare ( const BSONObj r,
const Ordering o,
bool  considerFieldName = true 
) const

wo='well ordered'.

fields must be in same order in each object. Ordering is with respect to the signs of the elements and allows ascending / descending key mixing.

Returns
<0 if l<r. 0 if l==r. >0 if l>r
int mongo::BSONObj::woCompare ( const BSONObj r,
const BSONObj ordering = BSONObj(),
bool  considerFieldName = true 
) const

wo='well ordered'.

fields must be in same order in each object. Ordering is with respect to the signs of the elements and allows ascending / descending key mixing.

Returns
<0 if l<r. 0 if l==r. >0 if l>r
int mongo::BSONObj::woSortOrder ( const BSONObj r,
const BSONObj sortKey,
bool  useDotted = false 
) const
Parameters
useDottedwhether to treat sort key fields as possibly dotted and expand into them

The documentation for this class was generated from the following files: