void IndexSpec::_init(){ assert( keyPattern.objsize() ); string pluginName = IndexPlugin::findPluginName( keyPattern ); BSONObjBuilder nullKeyB; BSONObjIterator i( keyPattern ); while( i.more() ) { BSONElement e = i.next(); _fieldNames.push_back( e.fieldName() ); _fixed.push_back( BSONElement() ); nullKeyB.appendNull( "" ); } _nullKey = nullKeyB.obj(); BSONObjBuilder b; b.appendNull( "" ); _nullObj = b.obj(); _nullElt = _nullObj.firstElement(); if ( pluginName.size() ){ IndexPlugin * plugin = IndexPlugin::get( pluginName ); if ( ! plugin ){ log() << "warning: can't find plugin [" << pluginName << "]" << endl; } else { _indexType.reset( plugin->generate( this ) ); } } _finishedInit = true; }
bool LastError::appendSelf(BSONObjBuilder& b, bool blankErr) const { if (!_valid) { if (blankErr) b.appendNull("err"); b.append("n", 0); return false; } if (_msg.empty()) { if (blankErr) { b.appendNull("err"); } } else { b.append("err", _msg); } if (_code) { b.append("code", _code); b.append("codeName", ErrorCodes::errorString(ErrorCodes::Error(_code))); } if (_updatedExisting != NotUpdate) b.appendBool("updatedExisting", _updatedExisting == True); if (!_upsertedId.isEmpty()) { b.append(_upsertedId[kUpsertedFieldName]); } b.appendNumber("n", _nObjects); return !_msg.empty(); }
void append( BSONObjBuilder& b , string name , jsval val , BSONType oldType = EOO , int depth=0 ) { //cout << "name: " << name << "\t" << typeString( val ) << " oldType: " << oldType << endl; switch ( JS_TypeOfValue( _context , val ) ) { case JSTYPE_VOID: b.appendUndefined( name.c_str() ); break; case JSTYPE_NULL: b.appendNull( name.c_str() ); break; case JSTYPE_NUMBER: { double d = toNumber( val ); if ( oldType == NumberInt && ((int)d) == d ) b.append( name.c_str() , (int)d ); else b.append( name.c_str() , d ); break; } case JSTYPE_STRING: b.append( name.c_str() , toString( val ) ); break; case JSTYPE_BOOLEAN: b.appendBool( name.c_str() , toBoolean( val ) ); break; case JSTYPE_OBJECT: { JSObject * o = JSVAL_TO_OBJECT( val ); if ( ! o || o == JSVAL_NULL ) { b.appendNull( name.c_str() ); } else if ( ! appendSpecialDBObject( this , b , name , val , o ) ) { BSONObj sub = toObject( o , depth ); if ( JS_IsArrayObject( _context , o ) ) { b.appendArray( name.c_str() , sub ); } else { b.append( name.c_str() , sub ); } } break; } case JSTYPE_FUNCTION: { string s = toString(val); if ( s[0] == '/' ) { appendRegex( b , name , s ); } else { b.appendCode( name.c_str() , getFunctionCode( val ).c_str() ); } break; } default: uassert( 10217 , (string)"can't append field. name:" + name + " type: " + typeString( val ) , 0 ); } }
void IndexSpec::_init() { verify( keyPattern.objsize() ); // some basics _nFields = keyPattern.nFields(); _sparse = info["sparse"].trueValue(); uassert( 13529 , "sparse only works for single field keys" , ! _sparse || _nFields ); { // build _nullKey BSONObjBuilder b; BSONObjIterator i( keyPattern ); while( i.more() ) { BSONElement e = i.next(); _fieldNames.push_back( e.fieldName() ); _fixed.push_back( BSONElement() ); b.appendNull( "" ); } _nullKey = b.obj(); } { // _nullElt BSONObjBuilder b; b.appendNull( "" ); _nullObj = b.obj(); _nullElt = _nullObj.firstElement(); } { // _undefinedElt BSONObjBuilder b; b.appendUndefined( "" ); _undefinedObj = b.obj(); _undefinedElt = _undefinedObj.firstElement(); } { // handle plugins string pluginName = IndexPlugin::findPluginName( keyPattern ); if ( pluginName.size() ) { IndexPlugin * plugin = IndexPlugin::get( pluginName ); if ( ! plugin ) { log() << "warning: can't find plugin [" << pluginName << "]" << endl; } else { _indexType.reset( plugin->generate( this ) ); } } } _finishedInit = true; }
BtreeKeyGenerator::BtreeKeyGenerator(vector<const char*> fieldNames, vector<BSONElement> fixed, bool isSparse) : _fieldNames(fieldNames), _isSparse(isSparse), _fixed(fixed) { BSONObjBuilder nullKeyBuilder; for (size_t i = 0; i < fieldNames.size(); ++i) { nullKeyBuilder.appendNull(""); } _nullKey = nullKeyBuilder.obj(); BSONObjBuilder nullEltBuilder; nullEltBuilder.appendNull(""); _nullObj = nullEltBuilder.obj(); _nullElt = _nullObj.firstElement(); }
void appendCommandResponse(PlanExecutor* exec, bool isRemove, const boost::optional<BSONObj>& value, BSONObjBuilder& result) { BSONObjBuilder lastErrorObjBuilder(result.subobjStart("lastErrorObject")); if (isRemove) { lastErrorObjBuilder.appendNumber("n", getDeleteStats(exec)->docsDeleted); } else { const UpdateStats* updateStats = getUpdateStats(exec); lastErrorObjBuilder.appendBool("updatedExisting", updateStats->nMatched > 0); lastErrorObjBuilder.appendNumber("n", updateStats->inserted ? 1 : updateStats->nMatched); // Note we have to use the objInserted from the stats here, rather than 'value' // because the _id field could have been excluded by a projection. if (!updateStats->objInserted.isEmpty()) { lastErrorObjBuilder.appendAs(updateStats->objInserted["_id"], kUpsertedFieldName); } } lastErrorObjBuilder.done(); if (value) { result.append("value", *value); } else { result.appendNull("value"); } }
INT32 _rtnSQLMax::result( BSONObjBuilder &builder ) { INT32 rc = SDB_OK ; try { if ( _ele.eoo() ) { builder.appendNull( _alias.toString() ) ; } else { builder.appendAs( _ele, _alias.toString() ) ; } _obj = BSONObj() ; _ele = BSONElement() ; } catch ( std::exception &e ) { PD_LOG( PDERROR, "unexcepted err happened:%s", e.what() ) ; rc = SDB_SYS ; goto error ; } done: return rc ; error: goto done ; }
// static BSONObj IndexLegacy::getMissingField(OperationContext* opCtx, Collection* collection, const BSONObj& infoObj) { BSONObj keyPattern = infoObj.getObjectField("key"); std::string accessMethodName; if (collection) accessMethodName = collection->getIndexCatalog()->getAccessMethodName(opCtx, keyPattern); else accessMethodName = IndexNames::findPluginName(keyPattern); if (IndexNames::HASHED == accessMethodName) { int hashVersion = infoObj["hashVersion"].numberInt(); HashSeed seed = infoObj["seed"].numberInt(); // Explicit null valued fields and missing fields are both represented in hashed indexes // using the hash value of the null BSONElement. This is partly for historical reasons // (hash of null was used in the initial release of hashed indexes and changing would // alter the data format). Additionally, in certain places the hashed index code and // the index bound calculation code assume null and missing are indexed identically. BSONObj nullObj = BSON("" << BSONNULL); return BSON("" << ExpressionKeysPrivate::makeSingleHashKey( nullObj.firstElement(), seed, hashVersion)); } else { BSONObjBuilder b; b.appendNull(""); return b.obj(); } }
void KVCatalog::FeatureTracker::putInfo(OperationContext* opCtx, const FeatureBits& versionInfo) { BSONObjBuilder bob; bob.appendBool(kIsFeatureDocumentFieldName, true); // We intentionally include the "ns" field with a null value in the feature document to prevent // older versions that do 'obj["ns"].String()' from starting up. This way only versions that are // aware of the feature document's existence can successfully start up. bob.appendNull(kNamespaceFieldName); bob.append(kNonRepairableFeaturesFieldName, static_cast<long long>(versionInfo.nonRepairableFeatures)); bob.append(kRepairableFeaturesFieldName, static_cast<long long>(versionInfo.repairableFeatures)); BSONObj obj = bob.done(); if (_rid.isNull()) { // This is the first time a feature is being marked as in-use or not in-use, so we must // insert the feature document rather than update it. const bool enforceQuota = false; // TODO SERVER-30638: using timestamp 0 for these inserts auto rid = _catalog->_rs->insertRecord( opCtx, obj.objdata(), obj.objsize(), Timestamp(), enforceQuota); fassert(40113, rid.getStatus()); _rid = rid.getValue(); } else { const bool enforceQuota = false; UpdateNotifier* notifier = nullptr; auto status = _catalog->_rs->updateRecord( opCtx, _rid, obj.objdata(), obj.objsize(), enforceQuota, notifier); fassert(40114, status); } }
MONGO_INITIALIZER(FTSIndexFormat)(InitializerContext* context) { BSONObjBuilder b; b.appendNull(""); nullObj = b.obj(); nullElt = nullObj.firstElement(); return Status::OK(); }
BSONObj RollbackFixUpInfo::SingleDocumentOperationDescription::toBSON() const { // For non-insert operations, we will use the collection UUID and document id to query the sync // source (using the source collection's default collation) for the most recent copy of the // deleted/updated document. This is necessary to complete the rollback for a deleted/updated // document. // Insert operations are rolled back by deleting the the document from the local collection. BSONObjBuilder bob; { BSONObjBuilder idBob(bob.subobjStart("_id")); _collectionUuid.appendToBuilder(&idBob, "collectionUuid"); idBob.append(_wrappedDocId.firstElement()); } // This matches the "op" field in the oplog entry. appendOpTypeToBuilder(_opType, &bob); // The database name is used in the find command request when fetching the document from the // sync source. bob.append("db", _dbName); // This will be replaced by the most recent copy of the affected document from the sync // source. If the document is not found on the sync source, this will remain null. bob.appendNull("documentToRestore"); return bob.obj(); }
// Get the index keys for elements that are GeoJSON. void S2AccessMethod::getGeoKeys(const BSONElementSet& elements, BSONObjSet* out) const { for (BSONElementSet::iterator i = elements.begin(); i != elements.end(); ++i) { uassert(16754, "Can't parse geometry from element: " + i->toString(), i->isABSONObj()); const BSONObj &obj = i->Obj(); vector<string> cells; bool succeeded = S2SearchUtil::getKeysForObject(obj, _params, &cells); uassert(16755, "Can't extract geo keys from object, malformed geometry?:" + obj.toString(), succeeded); uassert(16756, "Unable to generate keys for (likely malformed) geometry: " + obj.toString(), cells.size() > 0); for (vector<string>::const_iterator it = cells.begin(); it != cells.end(); ++it) { BSONObjBuilder b; b.append("", *it); out->insert(b.obj()); } } if (0 == out->size()) { BSONObjBuilder b; b.appendNull(""); out->insert(b.obj()); } }
Status AuthzManagerExternalState::getPrivilegeDocument(const UserName& userName, int authzVersion, BSONObj* result) { if (userName == internalSecurity.user->getName()) { return Status(ErrorCodes::InternalError, "Requested privilege document for the internal user"); } StringData dbname = userName.getDB(); // Make sure the dbname is actually a database if (dbname == StringData("$external", StringData::LiteralTag()) || dbname == AuthorizationManager::SERVER_RESOURCE_NAME || dbname == AuthorizationManager::CLUSTER_RESOURCE_NAME) { return Status(ErrorCodes::UserNotFound, mongoutils::str::stream() << "No privilege documents stored in the " << dbname << " user source."); } if (!NamespaceString::validDBName(dbname)) { return Status(ErrorCodes::BadValue, mongoutils::str::stream() << "Bad database name \"" << dbname << "\""); } // Build the query needed to get the privilege document std::string usersNamespace; BSONObjBuilder queryBuilder; if (authzVersion == 1) { usersNamespace = mongoutils::str::stream() << dbname << ".system.users"; queryBuilder.append(AuthorizationManager::V1_USER_NAME_FIELD_NAME, userName.getUser()); queryBuilder.appendNull(AuthorizationManager::V1_USER_SOURCE_FIELD_NAME); } else if (authzVersion == 2) { usersNamespace = "admin.system.users"; queryBuilder.append(AuthorizationManager::USER_NAME_FIELD_NAME, userName.getUser()); queryBuilder.append(AuthorizationManager::USER_SOURCE_FIELD_NAME, userName.getDB()); } else { return Status(ErrorCodes::UnsupportedFormat, mongoutils::str::stream() << "Unrecognized authorization format version: " << authzVersion); } // Query for the privilege document BSONObj userBSONObj; Status found = _findUser(usersNamespace, queryBuilder.obj(), &userBSONObj); if (!found.isOK()) { if (found.code() == ErrorCodes::UserNotFound) { // Return more detailed status that includes user name. return Status(ErrorCodes::UserNotFound, mongoutils::str::stream() << "auth: couldn't find user " << userName.toString() << ", " << usersNamespace, 0); } else { return found; } } *result = userBSONObj.getOwned(); return Status::OK(); }
Status AuthzManagerExternalState::getPrivilegeDocument(const std::string& dbname, const UserName& userName, BSONObj* result) const { if (dbname == StringData("$external", StringData::LiteralTag()) || dbname == AuthorizationManager::SERVER_RESOURCE_NAME || dbname == AuthorizationManager::CLUSTER_RESOURCE_NAME) { return Status(ErrorCodes::UserNotFound, mongoutils::str::stream() << "No privilege documents stored in the " << dbname << " user source."); } if (!NamespaceString::validDBName(dbname)) { return Status(ErrorCodes::BadValue, "Bad database name \"" + dbname + "\""); } if (userName == internalSecurity.user) { if (internalSecurity.pwd.empty()) { return Status(ErrorCodes::UserNotFound, "key file must be used to log in with internal user", 15889); } *result = BSON(AuthorizationManager::USER_NAME_FIELD_NAME << internalSecurity.user.getUser() << AuthorizationManager::PASSWORD_FIELD_NAME << internalSecurity.pwd).getOwned(); return Status::OK(); } std::string usersNamespace = dbname + ".system.users"; BSONObj userBSONObj; BSONObjBuilder queryBuilder; queryBuilder.append(AuthorizationManager::USER_NAME_FIELD_NAME, userName.getUser()); if (userName.getDB() == dbname) { queryBuilder.appendNull(AuthorizationManager::USER_SOURCE_FIELD_NAME); } else { queryBuilder.append(AuthorizationManager::USER_SOURCE_FIELD_NAME, userName.getDB()); } Status found = _findUser(usersNamespace, queryBuilder.obj(), &userBSONObj); if (!found.isOK()) { if (found.code() == ErrorCodes::UserNotFound) { // Return more detailed status that includes user name. return Status(ErrorCodes::UserNotFound, mongoutils::str::stream() << "auth: couldn't find user " << userName.toString() << ", " << usersNamespace, 0); } else { return found; } } *result = userBSONObj.getOwned(); return Status::OK(); }
Status AuthzManagerExternalState::getPrivilegeDocumentV1(const StringData& dbname, const UserName& userName, BSONObj* result) { if (userName == internalSecurity.user->getName()) { return Status(ErrorCodes::InternalError, "Requested privilege document for the internal user"); } if (!NamespaceString::validDBName(dbname)) { return Status(ErrorCodes::BadValue, mongoutils::str::stream() << "Bad database name \"" << dbname << "\""); } const bool isUserFromTargetDB = (dbname == userName.getDB()); // Build the query needed to get the privilege document BSONObjBuilder queryBuilder; const NamespaceString usersNamespace(dbname, "system.users"); queryBuilder.append(AuthorizationManager::V1_USER_NAME_FIELD_NAME, userName.getUser()); if (isUserFromTargetDB) { queryBuilder.appendNull(AuthorizationManager::V1_USER_SOURCE_FIELD_NAME); } else { queryBuilder.append(AuthorizationManager::V1_USER_SOURCE_FIELD_NAME, userName.getDB()); } // Query for the privilege document BSONObj userBSONObj; Status found = findOne(usersNamespace, queryBuilder.done(), &userBSONObj); if (!found.isOK()) { if (found.code() == ErrorCodes::NoMatchingDocument) { // Return more detailed status that includes user name. return Status(ErrorCodes::UserNotFound, mongoutils::str::stream() << "auth: couldn't find user " << userName.toString() << ", " << usersNamespace.ns(), 0); } else { return found; } } if (isUserFromTargetDB) { if (userBSONObj[AuthorizationManager::PASSWORD_FIELD_NAME].eoo()) { return Status(ErrorCodes::AuthSchemaIncompatible, mongoutils::str::stream() << "User documents with schema version " << AuthorizationManager::schemaVersion24 << " must have a \"" << AuthorizationManager::PASSWORD_FIELD_NAME << "\" field."); } } *result = userBSONObj.getOwned(); return Status::OK(); }
INT32 _coordCMDListCollection::_preProcess( rtnQueryOptions &queryOpt, string & clName, BSONObj &outSelector ) { BSONObjBuilder builder ; clName = CAT_COLLECTION_INFO_COLLECTION ; builder.appendNull( CAT_COLLECTION_NAME ) ; outSelector = queryOpt.getSelector() ; queryOpt.setSelector( builder.obj() ) ; return SDB_OK ; }
// Build a new BSONObj with root in it. If e is non-empty, append that to the key. Insert // the BSONObj into keys. void addKey(const string& root, const BSONElement& e, BSONObjSet& keys) const { BSONObjBuilder buf; buf.append("", root); if (e.eoo()) buf.appendNull(""); else buf.appendAs(e, ""); keys.insert(buf.obj()); }
void run() { create(); BSONObjSetDefaultOrder keys; id().getKeysFromObject( fromjson( "{a:[{b:1},{c:2}]}" ), keys ); checkSize( 2, keys ); BSONObjSetDefaultOrder::iterator i = keys.begin(); { BSONObjBuilder e; e.appendNull( "" ); e.append( "", 2 ); assertEquals( e.obj(), *i++ ); } { BSONObjBuilder e; e.append( "", 1 ); e.appendNull( "" ); assertEquals( e.obj(), *i++ ); } }
void testorder(){ { BSONObj x,y,z; { BSONObjBuilder b; b.append( "x" , (long long)2 ); x = b.obj(); } { BSONObjBuilder b; b.append( "x" , (int)3 ); y = b.obj(); } { BSONObjBuilder b; b.append( "x" , (long long)4 ); z = b.obj(); } assert( x.woCompare( y ) < 0 ); assert( x.woCompare( z ) < 0 ); assert( y.woCompare( x ) > 0 ); assert( z.woCompare( x ) > 0 ); assert( y.woCompare( z ) < 0 ); assert( z.woCompare( y ) > 0 ); } { BSONObj ll,d,i,n,u; { BSONObjBuilder b; b.append( "x" , (long long)2 ); ll = b.obj(); } { BSONObjBuilder b; b.append( "x" , (double)2 ); d = b.obj(); } { BSONObjBuilder b; b.append( "x" , (int)2 ); i = b.obj(); } { BSONObjBuilder b; b.appendNull( "x" ); n = b.obj(); } { BSONObjBuilder b; u = b.obj(); } assert( ll.woCompare( u ) == d.woCompare( u ) ); assert( ll.woCompare( u ) == i.woCompare( u ) ); BSONObj k = BSON( "x" << 1 ); assert( ll.woCompare( u , k ) == d.woCompare( u , k ) ); assert( ll.woCompare( u , k ) == i.woCompare( u , k ) ); assert( u.woCompare( ll ) == u.woCompare( d ) ); assert( u.woCompare( ll ) == u.woCompare( i ) ); assert( u.woCompare( ll , k ) == u.woCompare( d , k ) ); assert( u.woCompare( ll , k ) == u.woCompare( d , k ) ); assert( i.woCompare( n ) == d.woCompare( n ) ); assert( ll.woCompare( n ) == d.woCompare( n ) ); assert( ll.woCompare( n ) == i.woCompare( n ) ); assert( ll.woCompare( n , k ) == d.woCompare( n , k ) ); assert( ll.woCompare( n , k ) == i.woCompare( n , k ) ); assert( n.woCompare( ll ) == n.woCompare( d ) ); assert( n.woCompare( ll ) == n.woCompare( i ) ); assert( n.woCompare( ll , k ) == n.woCompare( d , k ) ); assert( n.woCompare( ll , k ) == n.woCompare( d , k ) ); } { BSONObj l,r; { BSONObjBuilder b; b.append( "x" , "eliot" ); l = b.obj(); } { BSONObjBuilder b; b.appendSymbol( "x" , "eliot" ); r = b.obj(); } assert( l.woCompare( r ) == 0 ); assert( r.woCompare( l ) == 0 ); } }
BtreeKeyGenerator::BtreeKeyGenerator(std::vector<const char*> fieldNames, std::vector<BSONElement> fixed, bool isSparse) : _fieldNames(fieldNames), _isSparse(isSparse), _fixed(fixed) { BSONObjBuilder nullKeyBuilder; for (size_t i = 0; i < fieldNames.size(); ++i) { nullKeyBuilder.appendNull(""); } _nullKey = nullKeyBuilder.obj(); _isIdIndex = fieldNames.size() == 1 && std::string("_id") == fieldNames[0]; }
// elements is a non-geo field. Add the values literally, expanding arrays. void getLiteralKeys(const BSONElementSet &elements, BSONObjSet *out) const { if (0 == elements.size()) { // Missing fields are indexed as null. BSONObjBuilder b; b.appendNull(""); out->insert(b.obj()); } else { for (BSONElementSet::iterator i = elements.begin(); i != elements.end(); ++i) { getOneLiteralKey(*i, out); } } }
void _add( const BSONObj& obj, const string& root , const BSONElement& e , BSONObjSet& keys ) const { BSONObjBuilder buf; buf.append( "" , root ); if ( e.eoo() ) buf.appendNull( "" ); else buf.appendAs( e , "" ); BSONObj key = buf.obj(); GEOQUADDEBUG( obj << "\n\t" << root << "\n\t" << key ); keys.insert( key ); }
/** * Suppress the "err" and "code" field if they are coming from a previous write error and * are not related to write concern. Also removes any write stats information (e.g. "n") * * Also, In some cases, 2.4 GLE w/ wOpTime can give us duplicate "err" and "code" fields b/c of * reporting a previous error. The later field is what we want - dedup and use later field. * * Returns the stripped GLE response. */ BSONObj stripNonWCInfo( const BSONObj& gleResponse ) { BSONObjIterator it( gleResponse ); BSONObjBuilder builder; BSONElement codeField; // eoo BSONElement errField; // eoo while ( it.more() ) { BSONElement el = it.next(); StringData fieldName( el.fieldName() ); if ( fieldName.compare( "err" ) == 0 ) { errField = el; } else if ( fieldName.compare( "code" ) == 0 ) { codeField = el; } else if ( fieldName.compare( "n" ) == 0 || fieldName.compare( "nModified" ) == 0 || fieldName.compare( "upserted" ) == 0 || fieldName.compare( "updatedExisting" ) == 0 ) { // Suppress field } else { builder.append( el ); } } if ( !codeField.eoo() ) { if ( !gleResponse["ok"].trueValue() ) { // The last code will be from the write concern builder.append( codeField ); } else { // The code is from a non-wc error on this connection - suppress it } } if ( !errField.eoo() ) { string err = errField.str(); if ( err == "norepl" || err == "noreplset" || err == "timeout" ) { // Append err if it's from a write concern issue builder.append( errField ); } else { // Suppress non-write concern err as null, but we need to report null err if ok if ( gleResponse["ok"].trueValue() ) builder.appendNull( errField.fieldName() ); } } return builder.obj(); }
INT32 _coordCMDListUser::_preProcess( rtnQueryOptions &queryOpt, string & clName, BSONObj &outSelector ) { BSONObjBuilder builder ; clName = AUTH_USR_COLLECTION ; if ( queryOpt.isSelectorEmpty() ) { builder.appendNull( FIELD_NAME_USER ) ; } queryOpt.setSelector( builder.obj() ) ; return SDB_OK ; }
TEST( AllMatchExpression, MatchesNull ) { BSONObjBuilder allArray; allArray.appendNull( "0" ); BSONObj operand = allArray.obj(); AllMatchExpression all; ASSERT( all.init( "a" ).isOK() ); all.getArrayFilterEntries()->addEquality( operand[0] ); ASSERT( all.matches( BSONObj(), NULL ) ); ASSERT( all.matches( BSON( "a" << BSONNULL ), NULL ) ); ASSERT( !all.matches( BSON( "a" << 4 ), NULL ) ); }
/* **************************************************************************** * * ContextAttribute::valueBson - * * Used to render attribute value to BSON, appended into the bsonAttr builder */ void ContextAttribute::valueBson(BSONObjBuilder& bsonAttr, const std::string& attrType, bool autocast, bool strings2numbers) const { if (compoundValueP == NULL) { bsonAppendAttrValue(bsonAttr, attrType, autocast); } else { if (compoundValueP->valueType == ValueTypeVector) { BSONArrayBuilder b; compoundValueBson(compoundValueP->childV, b, strings2numbers); bsonAttr.append(ENT_ATTRS_VALUE, b.arr()); } else if (compoundValueP->valueType == ValueTypeObject) { BSONObjBuilder b; compoundValueBson(compoundValueP->childV, b, strings2numbers); bsonAttr.append(ENT_ATTRS_VALUE, b.obj()); } else if (compoundValueP->valueType == ValueTypeString) { // FIXME P4: this is somehow redundant. See https://github.com/telefonicaid/fiware-orion/issues/271 bsonAttr.append(ENT_ATTRS_VALUE, compoundValueP->stringValue); } else if (compoundValueP->valueType == ValueTypeNumber) { // FIXME P4: this is somehow redundant. See https://github.com/telefonicaid/fiware-orion/issues/271 bsonAttr.append(ENT_ATTRS_VALUE, compoundValueP->numberValue); } else if (compoundValueP->valueType == ValueTypeBoolean) { // FIXME P4: this is somehow redundant. See https://github.com/telefonicaid/fiware-orion/issues/271 bsonAttr.append(ENT_ATTRS_VALUE, compoundValueP->boolValue); } else if (compoundValueP->valueType == ValueTypeNull) { // FIXME P4: this is somehow redundant. See https://github.com/telefonicaid/fiware-orion/issues/271 bsonAttr.appendNull(ENT_ATTRS_VALUE); } else if (compoundValueP->valueType == ValueTypeNotGiven) { LM_E(("Runtime Error (value not given in compound value)")); } else { LM_E(("Runtime Error (Unknown type in compound value)")); } } }
BSONObj _qgmSelector::selector() const { BSONObjBuilder builder ; qgmOPFieldVec::const_iterator itr = _selector.begin() ; for ( ; itr != _selector.end(); itr++ ) { if ( !itr->value.attr().empty() ) { builder.appendNull( itr->value.attr().toString()) ; } } return builder.obj() ; }
void _appendHelper( BSONObjBuilder& result , const BSONObj& doc , bool found , const BSONObj& fields ) { if ( ! found ) { result.appendNull( "value" ); return; } if ( fields.isEmpty() ) { result.append( "value" , doc ); return; } Projection p; p.init( fields ); result.append( "value" , p.transform( doc ) ); }
/* makes a new BSONObj with the fields specified in pattern. fields returned in the order they appear in pattern. if any field missing or undefined in the original object, that field in the output will be null. n^2 implementation bad if pattern and object have lots of fields - normally pattern doesn't so should be fine. */ BSONObj BSONObj::extractFieldsDotted(BSONObj pattern) const { BSONObjBuilder b; BSONObjIterator i(pattern); while (i.more()) { BSONElement e = i.next(); const char *name = e.fieldName(); BSONElement x = getFieldDotted( name ); if ( x.eoo() || x.type() == Undefined ) { b.appendNull(name); } else { b.appendAs(x, name); } } return b.done(); }
// Get the index keys for elements that are GeoJSON. void S2AccessMethod::getGeoKeys(const BSONElementSet& elements, BSONObjSet* out) const { S2RegionCoverer coverer; _params.configureCoverer(&coverer); // See here for GeoJSON format: geojson.org/geojson-spec.html for (BSONElementSet::iterator i = elements.begin(); i != elements.end(); ++i) { uassert(16754, "Can't parse geometry from element: " + i->toString(), i->isABSONObj()); const BSONObj &obj = i->Obj(); vector<string> cells; S2Polyline line; S2Cell point; // We only support GeoJSON polygons. Why?: // 1. we don't automagically do WGS84/flat -> WGS84, and // 2. the old polygon format must die. if (GeoParser::isGeoJSONPolygon(obj)) { S2Polygon polygon; GeoParser::parseGeoJSONPolygon(obj, &polygon); keysFromRegion(&coverer, polygon, &cells); } else if (GeoParser::parseLineString(obj, &line)) { keysFromRegion(&coverer, line, &cells); } else if (GeoParser::parsePoint(obj, &point)) { S2CellId parent(point.id().parent(_params.finestIndexedLevel)); cells.push_back(parent.toString()); } else { uasserted(16755, "Can't extract geo keys from object, malformed geometry?:" + obj.toString()); } uassert(16756, "Unable to generate keys for (likely malformed) geometry: " + obj.toString(), cells.size() > 0); for (vector<string>::const_iterator it = cells.begin(); it != cells.end(); ++it) { BSONObjBuilder b; b.append("", *it); out->insert(b.obj()); } } if (0 == out->size()) { BSONObjBuilder b; b.appendNull(""); out->insert(b.obj()); } }