BSONObj DocumentSourceGeoNear::buildGeoNearCmd() const { // this is very similar to sourceToBson, but slightly different. // differences will be noted. BSONObjBuilder geoNear; // not building a subField geoNear.append("geoNear", pExpCtx->ns.coll()); // not in toBson if (coordsIsArray) { geoNear.appendArray("near", coords); } else { geoNear.append("near", coords); } geoNear.append("num", limit); // called limit in toBson if (maxDistance > 0) geoNear.append("maxDistance", maxDistance); if (minDistance > 0) geoNear.append("minDistance", minDistance); geoNear.append("query", query); geoNear.append("spherical", spherical); geoNear.append("distanceMultiplier", distanceMultiplier); if (includeLocs) geoNear.append("includeLocs", true); // String in toBson return geoNear.obj(); }
void DocumentSourceGeoNear::sourceToBson(BSONObjBuilder *pBuilder, bool explain) const { BSONObjBuilder geoNear (pBuilder->subobjStart("$geoNear")); if (coordsIsArray) { geoNear.appendArray("near", coords); } else { geoNear.append("near", coords); } geoNear.append("distanceField", distanceField->getPath(false)); // not in buildGeoNearCmd geoNear.append("limit", limit); if (maxDistance > 0) geoNear.append("maxDistance", maxDistance); geoNear.append("query", query); geoNear.append("spherical", spherical); geoNear.append("distanceMultiplier", distanceMultiplier); if (includeLocs) geoNear.append("includeLocs", includeLocs->getPath(false)); geoNear.append("uniqueDocs", uniqueDocs); geoNear.doneFast(); }
INT32 rtnSQLAddToSet::result( BSONObjBuilder &builder ) { INT32 rc = SDB_OK; PD_CHECK( !_alias.empty(), SDB_INVALIDARG, error, PDERROR, "no aliases for function!" ); try { builder.appendArray( _alias.toString(), _pArrBuilder->arr() ); SDB_OSS_DEL _pArrBuilder; _fieldSet.clear(); _objVec.clear(); _pArrBuilder = SDB_OSS_NEW BSONArrayBuilder(); PD_CHECK( _pArrBuilder != NULL, SDB_OOM, error, PDERROR, "malloc failed" ); } catch( std::exception &e ) { PD_LOG( PDERROR, "received unexpected error:%s", e.what() ); rc = SDB_SYS; goto error; } done: return rc; error: goto done; }
virtual bool run(const string& dbname , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) { string p = cmdObj.firstElement().String(); if ( p == "*" ) { vector<string> names; RamLog::getNames( names ); BSONArrayBuilder arr; for ( unsigned i=0; i<names.size(); i++ ) { arr.append( names[i] ); } result.appendArray( "names" , arr.arr() ); } else { RamLog* ramlog = RamLog::getIfExists(p); if ( ! ramlog ) { errmsg = str::stream() << "no RamLog named: " << p; return false; } RamLog::LineIterator rl(ramlog); result.appendNumber( "totalLinesWritten", rl.getTotalLinesWritten() ); BSONArrayBuilder arr( result.subarrayStart( "log" ) ); while (rl.more()) arr.append(rl.next()); arr.done(); } return true; }
BSONObj listFiles(const BSONObj& args){ uassert( "need to specify 1 argument to listFiles" , args.nFields() == 1 ); BSONObjBuilder lst; string rootname = args.firstElement().valuestrsafe(); path root( rootname ); directory_iterator end; directory_iterator i( root); int num =0; while ( i != end ){ path p = *i; BSONObjBuilder b; b << "name" << p.string(); b.appendBool( "isDirectory", is_directory( p ) ); stringstream ss; ss << num; string name = ss.str(); lst.append( name.c_str(), b.done() ); num++; i++; } BSONObjBuilder ret; ret.appendArray( "", lst.done() ); return ret.obj(); }
virtual bool run(const string& dbname , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) { string p = cmdObj.firstElement().String(); if ( p == "*" ) { vector<string> names; RamLog::getNames( names ); BSONArrayBuilder arr; for ( unsigned i=0; i<names.size(); i++ ) { arr.append( names[i] ); } result.appendArray( "names" , arr.arr() ); } else { RamLog* rl = RamLog::get( p ); if ( ! rl ) { errmsg = str::stream() << "no RamLog named: " << p; return false; } result.appendNumber( "totalLinesWritten", rl->getTotalLinesWritten() ); vector<const char*> lines; rl->get( lines ); BSONArrayBuilder arr( result.subarrayStart( "log" ) ); for ( unsigned i=0; i<lines.size(); i++ ) arr.append( lines[i] ); arr.done(); } return true; }
void Projection::append( BSONObjBuilder& b , const BSONElement& e ) const { FieldMap::const_iterator field = _fields.find( e.fieldName() ); if (field == _fields.end()) { if (_include) b.append(e); } else { Projection& subfm = *field->second; if ((subfm._fields.empty() && !subfm._special) || !(e.type()==Object || e.type()==Array) ) { if (subfm._include) b.append(e); } else if (e.type() == Object) { BSONObjBuilder subb; BSONObjIterator it(e.embeddedObject()); while (it.more()) { subfm.append(subb, it.next()); } b.append(e.fieldName(), subb.obj()); } else { //Array BSONObjBuilder subb; subfm.appendArray(subb, e.embeddedObject()); b.appendArray(e.fieldName(), subb.obj()); } } }
BSONObj build( int depth ){ BSONObjBuilder b; b.append( "0" , depth ); if ( depth > 0 ) b.appendArray( "1" , build( depth - 1 ) ); return b.obj(); }
void Pipeline::writeExplainShard(BSONObjBuilder &result) const { BSONArrayBuilder opArray; // where we'll put the pipeline ops // next, add the pipeline operators writeExplainOps(&opArray); result.appendArray(serverPipelineName, opArray.arr()); }
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 ); } }
virtual bool run(OperationContext* txn, const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool fromRepl) { BSONObj configObj; if( cmdObj["replSetInitiate"].type() == Object ) { configObj = cmdObj["replSetInitiate"].Obj(); } if (configObj.isEmpty()) { result.append("info2", "no configuration explicitly specified -- making one"); log() << "replSet info initiate : no configuration specified. " "Using a default configuration for the set"; ReplicationCoordinatorExternalStateImpl externalState; std::string name; std::vector<HostAndPort> seeds; std::set<HostAndPort> seedSet; parseReplSetSeedList( &externalState, getGlobalReplicationCoordinator()->getSettings().replSet, name, seeds, seedSet); // may throw... BSONObjBuilder b; b.append("_id", name); b.append("version", 1); BSONObjBuilder members; HostAndPort me = someHostAndPortForMe(); members.append("0", BSON( "_id" << 0 << "host" << me.toString() )); result.append("me", me.toString()); for( unsigned i = 0; i < seeds.size(); i++ ) { members.append(BSONObjBuilder::numStr(i+1), BSON( "_id" << i+1 << "host" << seeds[i].toString())); } b.appendArray("members", members.obj()); configObj = b.obj(); log() << "replSet created this configuration for initiation : " << configObj.toString(); } if (configObj.getField("version").eoo()) { // Missing version field defaults to version 1. BSONObjBuilder builder; builder.appendElements(configObj); builder.append("version", 1); configObj = builder.obj(); } Status status = getGlobalReplicationCoordinator()->processReplSetInitiate(txn, configObj, &result); return appendCommandStatus(result, status); }
bool GroupCommand::run(OperationContext* txn, const std::string& dbname, BSONObj& cmdObj, int, std::string& errmsg, BSONObjBuilder& out, bool fromRepl) { GroupRequest groupRequest; Status parseRequestStatus = parseRequest(dbname, cmdObj, &groupRequest); if (!parseRequestStatus.isOK()) { return appendCommandStatus(out, parseRequestStatus); } AutoGetCollectionForRead ctx(txn, groupRequest.ns); Collection* coll = ctx.getCollection(); PlanExecutor *rawPlanExecutor; Status getExecStatus = getExecutorGroup(txn, coll, groupRequest, PlanExecutor::YIELD_AUTO, &rawPlanExecutor); if (!getExecStatus.isOK()) { return appendCommandStatus(out, getExecStatus); } scoped_ptr<PlanExecutor> planExecutor(rawPlanExecutor); // Group executors return ADVANCED exactly once, with the entire group result. BSONObj retval; PlanExecutor::ExecState state = planExecutor->getNext(&retval, NULL); if (PlanExecutor::ADVANCED != state) { if (PlanExecutor::FAILURE == state && WorkingSetCommon::isValidStatusMemberObject(retval)) { return appendCommandStatus(out, WorkingSetCommon::getMemberObjectStatus(retval)); } return appendCommandStatus(out, Status(ErrorCodes::BadValue, str::stream() << "error encountered during group " << "operation, executor returned " << PlanExecutor::statestr(state))); } invariant(planExecutor->isEOF()); invariant(STAGE_GROUP == planExecutor->getRootStage()->stageType()); GroupStage* groupStage = static_cast<GroupStage*>(planExecutor->getRootStage()); const GroupStats* groupStats = static_cast<const GroupStats*>(groupStage->getSpecificStats()); const CommonStats* groupChildStats = groupStage->getChildren()[0]->getCommonStats(); out.appendArray("retval", retval); out.append("count", static_cast<long long>(groupChildStats->advanced)); out.append("keys", static_cast<long long>(groupStats->nGroups)); return true; }
bool DBClientWithCommands::eval(const string &dbname, const string &jscode, BSONObj& info, BSONElement& retValue, BSONObj *args) { BSONObjBuilder b; b.appendCode("$eval", jscode.c_str()); if ( args ) b.appendArray("args", *args); bool ok = runCommand(dbname, b.done(), info); if ( ok ) retValue = info.getField("retval"); return ok; }
INT32 rtnCoordDelete::buildOpMsg( const CoordCataInfoPtr &cataInfo, const CoordSubCLlist &subCLList, CHAR *pSrcMsg, CHAR *&pDstMsg, INT32 &bufferSize ) { INT32 rc = SDB_OK; INT32 flag; CHAR *pCollectionName = NULL; CHAR *pDeletor = NULL; CHAR *pHint = NULL; BSONObj boDeletor; BSONObj boHint; rc = msgExtractDelete( pSrcMsg, &flag, &pCollectionName, &pDeletor, &pHint ); PD_RC_CHECK( rc, PDERROR, "failed to parse delete request(rc=%d)", rc ); try { boDeletor = BSONObj( pDeletor ); boHint = BSONObj( pHint ); BSONArrayBuilder babSubCL; CoordSubCLlist::const_iterator iterCL = subCLList.begin(); while( iterCL != subCLList.end() ) { babSubCL.append( *iterCL ); ++iterCL; } BSONObjBuilder bobNewDeletor; bobNewDeletor.appendElements( boDeletor ); bobNewDeletor.appendArray( CAT_SUBCL_NAME, babSubCL.arr() ); BSONObj boNewDeletor = bobNewDeletor.obj(); rc = msgBuildDeleteMsg( &pDstMsg, &bufferSize, pCollectionName, flag, 0, &boNewDeletor, &boHint ); PD_RC_CHECK( rc, PDERROR, "failed to build delete request(rc=%d)", rc ); { MsgOpDelete *pReqMsg = (MsgOpDelete *)pDstMsg; MsgOpDelete *pSrcReq = (MsgOpDelete *)pSrcMsg; pReqMsg->version = cataInfo->getVersion(); pReqMsg->w = pSrcReq->w; } } catch ( std::exception &e ) { PD_RC_CHECK( SDB_INVALIDARG, PDERROR, "occur unexpected error:%s", e.what() ); } done: return rc; error: goto done; }
void Projection::append( BSONObjBuilder& b , const BSONElement& e, const MatchDetails* details, const ArrayOpType arrayOpType ) const { FieldMap::const_iterator field = _fields.find( e.fieldName() ); if (field == _fields.end()) { if (_include) b.append(e); } else { Projection& subfm = *field->second; if ( ( subfm._fields.empty() && !subfm._special ) || !(e.type()==Object || e.type()==Array) ) { // field map empty, or element is not an array/object if (subfm._include) b.append(e); } else if (e.type() == Object) { BSONObjBuilder subb; BSONObjIterator it(e.embeddedObject()); while (it.more()) { subfm.append(subb, it.next(), details, arrayOpType); } b.append(e.fieldName(), subb.obj()); } else { //Array BSONObjBuilder matchedBuilder; if ( details && ( arrayOpType == ARRAY_OP_POSITIONAL || arrayOpType == ARRAY_OP_POSITIONAL_KEYED )) { // $ positional operator specified LOG(4) << "projection: checking if element " << e << " matched spec: " << getSpec() << " match details: " << *details << endl; uassert( 16352, mongoutils::str::stream() << "positional operator (" << e.fieldName() << ".$) requires corresponding field in query specifier", details && details->hasElemMatchKey() ); uassert( 16353, "positional operator element mismatch", ! e.embeddedObject()[details->elemMatchKey()].eoo() ); // append as the first element in the projected array matchedBuilder.appendAs( e.embeddedObject()[details->elemMatchKey()], "0" ); // append the key as the second element in the projected array if ( arrayOpType == ARRAY_OP_POSITIONAL_KEYED ) { matchedBuilder.append( "1", details->elemMatchKey() ); } } else { // append exact array; no subarray matcher specified subfm.appendArray( matchedBuilder, e.embeddedObject() ); } b.appendArray( e.fieldName(), matchedBuilder.obj() ); } } }
bool run(const char *ns, BSONObj& cmdObj, string& errmsg, BSONObjBuilder& result, bool){ string dbName = getDBName( ns ); string collection = cmdObj.firstElement().valuestrsafe(); string fullns = dbName + "." + collection; DBConfig * conf = grid.getDBConfig( dbName , false ); if ( ! conf || ! conf->isShardingEnabled() || ! conf->isSharded( fullns ) ){ return passthrough( conf , cmdObj , result ); } ChunkManager * cm = conf->getChunkManager( fullns ); massert( "how could chunk manager be null!" , cm ); vector<Chunk*> chunks; cm->getChunksForQuery( chunks , BSONObj() ); set<BSONObj,BSONObjCmp> all; int size = 32; for ( vector<Chunk*>::iterator i = chunks.begin() ; i != chunks.end() ; i++ ){ Chunk * c = *i; ScopedDbConnection conn( c->getShard() ); BSONObj res; bool ok = conn->runCommand( conf->getName() , cmdObj , res ); conn.done(); if ( ! ok ){ result.appendElements( res ); return false; } BSONObjIterator it( res["values"].embeddedObjectUserCheck() ); while ( it.more() ){ BSONElement nxt = it.next(); BSONObjBuilder temp(32); temp.appendAs( nxt , "x" ); all.insert( temp.obj() ); } } BSONObjBuilder b( size ); int n=0; for ( set<BSONObj,BSONObjCmp>::iterator i = all.begin() ; i != all.end(); i++ ){ b.appendAs( i->firstElement() , b.numStr( n++ ).c_str() ); } result.appendArray( "values" , b.obj() ); result.append( "ok" , 1 ); return true; }
bool Pipeline::run(BSONObjBuilder &result, string &errmsg) { massert(16600, "should not have an empty pipeline", !sources.empty()); /* chain together the sources we found */ DocumentSource* prevSource = sources.front().get(); for(SourceContainer::iterator iter(sources.begin() + 1), listEnd(sources.end()); iter != listEnd; ++iter) { intrusive_ptr<DocumentSource> pTemp(*iter); pTemp->setSource(prevSource); prevSource = pTemp.get(); } /* Iterate through the resulting documents, and add them to the result. We do this even if we're doing an explain, in order to capture the document counts and other stats. However, we don't capture the result documents for explain. */ if (explain) { if (!pCtx->getInRouter()) writeExplainShard(result); else { writeExplainMongos(result); } } else { // the array in which the aggregation results reside // cant use subArrayStart() due to error handling BSONArrayBuilder resultArray; DocumentSource* finalSource = sources.back().get(); for(bool hasDoc = !finalSource->eof(); hasDoc; hasDoc = finalSource->advance()) { Document pDocument(finalSource->getCurrent()); /* add the document to the result set */ BSONObjBuilder documentBuilder (resultArray.subobjStart()); pDocument->toBson(&documentBuilder); documentBuilder.doneFast(); // object will be too large, assert. the extra 1KB is for headers uassert(16389, str::stream() << "aggregation result exceeds maximum document size (" << BSONObjMaxUserSize / (1024 * 1024) << "MB)", resultArray.len() < BSONObjMaxUserSize - 1024); } resultArray.done(); result.appendArray("result", resultArray.arr()); } return true; }
TEST( ExpressionParserArrayTest, AllBadRegexArg ) { string tooLargePattern( 50 * 1000, 'z' ); BSONObjBuilder allArray; allArray.appendRegex( "0", tooLargePattern, "" ); BSONObjBuilder operand; operand.appendArray( "$all", allArray.obj() ); BSONObj query = BSON( "x" << operand.obj() ); StatusWithExpression result = ExpressionParser::parse( query ); ASSERT_FALSE( result.isOK() ); }
void Pipeline::writeExplainShard( BSONObjBuilder &result, const intrusive_ptr<DocumentSource> &pInputSource) const { BSONArrayBuilder opArray; // where we'll put the pipeline ops // first the cursor, which isn't in the opArray pInputSource->addToBsonArray(&opArray, true); // next, add the pipeline operators writeExplainOps(&opArray); result.appendArray(serverPipelineName, opArray.arr()); }
BSONObj rtnCoordDelete::_buildNewDeletor( const BSONObj &deletor, const CoordSubCLlist &subCLList ) { BSONObjBuilder builder ; BSONArrayBuilder babSubCL ; CoordSubCLlist::const_iterator iterCL = subCLList.begin(); while( iterCL != subCLList.end() ) { babSubCL.append( *iterCL ) ; ++iterCL ; } builder.appendElements( deletor ) ; builder.appendArray( CAT_SUBCL_NAME, babSubCL.arr() ) ; return builder.obj() ; }
/** * Appends info about all active client shard connections to a BOBuilder */ void ActiveClientConnections::appendInfo( BSONObjBuilder& b ) { BSONArrayBuilder arr( 64 * 1024 ); // There may be quite a few threads { scoped_lock lock( _mutex ); for ( set<const ClientConnections*>::const_iterator i = _clientConnections.begin(); i != _clientConnections.end(); ++i ) { BSONObjBuilder bb( arr.subobjStart() ); (*i)->appendInfo( bb ); bb.done(); } } b.appendArray( "threads", arr.obj() ); }
BSONObj listFiles(const BSONObj& _args){ static BSONObj cd = BSON( "0" << "." ); BSONObj args = _args.isEmpty() ? cd : _args; uassert( 10257 , "need to specify 1 argument to listFiles" , args.nFields() == 1 ); BSONObjBuilder lst; string rootname = args.firstElement().valuestrsafe(); path root( rootname ); stringstream ss; ss << "listFiles: no such directory: " << rootname; string msg = ss.str(); uassert( 12581, msg.c_str(), boost::filesystem::exists( root ) ); directory_iterator end; directory_iterator i( root); int num =0; while ( i != end ){ path p = *i; BSONObjBuilder b; b << "name" << p.string(); b.appendBool( "isDirectory", is_directory( p ) ); if ( ! is_directory( p ) ){ try { b.append( "size" , (double)file_size( p ) ); } catch ( ... ){ i++; continue; } } stringstream ss; ss << num; string name = ss.str(); lst.append( name, b.done() ); num++; i++; } BSONObjBuilder ret; ret.appendArray( "", lst.done() ); return ret.obj(); }
TEST( ExpressionParserArrayTest, AllRegex2 ) { BSONObjBuilder allArray; allArray.appendRegex( "0", "^a", "" ); allArray.append( "1", "abc" ); BSONObjBuilder all; all.appendArray( "$all", allArray.obj() ); BSONObj query = BSON( "a" << all.obj() ); StatusWithExpression result = ExpressionParser::parse( query ); ASSERT_TRUE( result.isOK() ); BSONObj notMatchFirst = BSON( "a" << "ax" ); BSONObj matchesBoth = BSON( "a" << "abc" ); ASSERT( !result.getValue()->matchesSingleElement( notMatchFirst[ "a" ] ) ); ASSERT( result.getValue()->matchesSingleElement( matchesBoth[ "a" ] ) ); }
void b(){ BSONObjBuilder b; b << "name" << "abc"; b.appendBool( "partitioned" , true ); b << "primary" << "myserver"; BSONObjBuilder a; a << "abc.foo" << fromjson( "{ 'key' : { 'a' : 1 } , 'unique' : false }" ); a << "abc.bar" << fromjson( "{ 'key' : { 'kb' : -1 } , 'unique' : true }" ); b.appendArray( "sharded" , a.obj() ); DBConfig c; testInOut( c , b.obj() ); assert( c.isSharded( "abc.foo" ) ); assert( ! c.isSharded( "abc.food" ) ); }
int main(int argc, char *argv[]) { BSONObjBuilder data; data.append("title", "this is title"); BSONObjBuilder arr; BSONObjBuilder subdata1; subdata1.append("anchor", "this is anchor"); subdata1.append("href", "this is href"); BSONObjBuilder subdata2; subdata2.append("anchor", "this is anchor"); subdata2.append("href", "this is href"); arr.append("link1", subdata1.obj()); arr.append("link2", subdata2.obj()); data.appendArray("links", arr.obj()); printf("%s\n", data.obj().toString().c_str()); return 0; }
void b() { BSONObjBuilder b; b << "name" << "abc"; b.appendBool( "partitioned" , true ); b << "primary" << "myserver"; BSONObjBuilder a; a << "abc.foo" << BSON( "a" << 1 ); a << "abc.bar" << BSON( "b" << -1 ); b.appendArray( "sharded" , a.obj() ); DBConfig c; testInOut( c , b.obj() ); assert( c.sharded( "abc.foo" ) ); assert( ! c.sharded( "abc.food" ) ); }
void Projection::transform( const BSONObj& in , BSONObjBuilder& b, const MatchDetails* details ) const { const ArrayOpType& arrayOpType = getArrayOpType(); BSONObjIterator i(in); while ( i.more() ) { BSONElement e = i.next(); if ( mongoutils::str::equals( "_id" , e.fieldName() ) ) { if ( _includeID ) b.append( e ); } else { Matchers::const_iterator matcher = _matchers.find( e.fieldName() ); if ( matcher == _matchers.end() ) { // no array projection matchers for this field append( b, e, details, arrayOpType ); } else { // field has array projection with $elemMatch specified. massert( 16348, "matchers are only supported for $elemMatch", arrayOpType == ARRAY_OP_ELEM_MATCH ); MatchDetails arrayDetails; arrayDetails.requestElemMatchKey(); if ( matcher->second->matches( in, &arrayDetails ) ) { LOG(4) << "Matched array on field: " << matcher->first << endl << " from array: " << in.getField( matcher->first ) << endl << " in object: " << in << endl << " at position: " << arrayDetails.elemMatchKey() << endl; FieldMap::const_iterator field = _fields.find( e.fieldName() ); massert( 16349, "$elemMatch specified, but projection field not found.", field != _fields.end() ); BSONArrayBuilder a; BSONObjBuilder o; massert( 16350, "$elemMatch called on document element with eoo", ! in.getField( e.fieldName() ).eoo() ); massert( 16351, "$elemMatch called on array element with eoo", ! in.getField( e.fieldName() ).Obj().getField( arrayDetails.elemMatchKey() ).eoo() ); a.append( in.getField( e.fieldName() ).Obj() .getField( arrayDetails.elemMatchKey() ) ); o.appendArray( matcher->first, a.arr() ); append( b, o.done().firstElement(), details, arrayOpType ); } } } } }
BSONObj listFiles(const BSONObj& _args, void* data) { BSONObj cd = BSON( "0" << "." ); BSONObj args = _args.isEmpty() ? cd : _args; uassert( 10257 , "need to specify 1 argument to listFiles" , args.nFields() == 1 ); BSONArrayBuilder lst; string rootname = args.firstElement().valuestrsafe(); boost::filesystem::path root( rootname ); stringstream ss; ss << "listFiles: no such directory: " << rootname; string msg = ss.str(); uassert( 12581, msg.c_str(), boost::filesystem::exists( root ) ); boost::filesystem::directory_iterator end; boost::filesystem::directory_iterator i( root); while ( i != end ) { boost::filesystem::path p = *i; BSONObjBuilder b; #if BOOST_VERSION >= 104400 b << "name" << p.generic_string(); #else b << "name" << p.string(); #endif b.appendBool( "isDirectory", is_directory( p ) ); if ( ! boost::filesystem::is_directory( p ) ) { try { b.append( "size" , (double)boost::filesystem::file_size( p ) ); } catch ( ... ) { i++; continue; } } lst.append( b.obj() ); i++; } BSONObjBuilder ret; ret.appendArray( "", lst.done() ); return ret.obj(); }
//b will be the value part of an array-typed BSONElement void Projection::appendArray( BSONObjBuilder& b , const BSONObj& a , bool nested) const { int skip = nested ? 0 : _skip; int limit = nested ? -1 : _limit; if (skip < 0) { skip = max(0, skip + a.nFields()); } int i=0; BSONObjIterator it(a); while (it.more()) { BSONElement e = it.next(); if (skip) { skip--; continue; } if (limit != -1 && (limit-- == 0)) { break; } switch(e.type()) { case Array: { BSONObjBuilder subb; appendArray(subb , e.embeddedObject(), true); b.appendArray(b.numStr(i++), subb.obj()); break; } case Object: { BSONObjBuilder subb; BSONObjIterator jt(e.embeddedObject()); while (jt.more()) { append(subb , jt.next()); } b.append(b.numStr(i++), subb.obj()); break; } default: if (_include) b.appendAs(e, b.numStr(i++)); } } }
void Scope::append( BSONObjBuilder & builder , const char * fieldName , const char * scopeName ){ int t = type( scopeName ); switch ( t ){ case Object: builder.append( fieldName , getObject( scopeName ) ); break; case Array: builder.appendArray( fieldName , getObject( scopeName ) ); break; case NumberDouble: builder.append( fieldName , getNumber( scopeName ) ); break; case NumberInt: builder.append( fieldName , getNumberInt( scopeName ) ); break; case NumberLong: builder.append( fieldName , getNumberLongLong( scopeName ) ); break; case String: builder.append( fieldName , getString( scopeName ).c_str() ); break; case Bool: builder.appendBool( fieldName , getBoolean( scopeName ) ); break; case jstNULL: case Undefined: builder.appendNull( fieldName ); break; case Date: // TODO: make signed builder.appendDate( fieldName , Date_t((unsigned long long)getNumber( scopeName )) ); break; case Code: builder.appendCode( fieldName , getString( scopeName ) ); break; default: stringstream temp; temp << "can't append type from:"; temp << t; uassert( 10206 , temp.str() , 0 ); } }