当前位置: 首页>>代码示例>>C++>>正文


C++ BSONObjBuilder::appendElements方法代码示例

本文整理汇总了C++中BSONObjBuilder::appendElements方法的典型用法代码示例。如果您正苦于以下问题:C++ BSONObjBuilder::appendElements方法的具体用法?C++ BSONObjBuilder::appendElements怎么用?C++ BSONObjBuilder::appendElements使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在BSONObjBuilder的用法示例。


在下文中一共展示了BSONObjBuilder::appendElements方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: handleSpecialNamespaces

// TODO: remove after MongoDB 3.2
bool Strategy::handleSpecialNamespaces(OperationContext* txn, Request& request, QueryMessage& q) {
    const char* ns = strstr(request.getns(), ".$cmd.sys.");
    if (!ns)
        return false;
    ns += 10;

    BSONObjBuilder reply;

    const auto upgradeToRealCommand = [txn, &q, &reply](StringData commandName) {
        BSONObjBuilder cmdBob;
        cmdBob.append(commandName, 1);
        cmdBob.appendElements(q.query);  // fields are validated by Commands
        auto interposedCmd = cmdBob.done();
        // Rewrite upgraded pseudoCommands to run on the 'admin' database.
        NamespaceString interposedNss("admin", "$cmd");
        Command::runAgainstRegistered(
            txn, interposedNss.ns().c_str(), interposedCmd, reply, q.queryOptions);
    };

    if (strcmp(ns, "inprog") == 0) {
        upgradeToRealCommand("currentOp");
    } else if (strcmp(ns, "killop") == 0) {
        upgradeToRealCommand("killOp");
    } else if (strcmp(ns, "unlock") == 0) {
        reply.append("err", "can't do unlock through mongos");
    } else {
        warning() << "unknown sys command [" << ns << "]";
        return false;
    }

    BSONObj x = reply.done();
    replyToQuery(0, request.p(), request.m(), x);
    return true;
}
开发者ID:FHIRBUFF,项目名称:mongo,代码行数:35,代码来源:strategy.cpp

示例2: remove

    Status AuthzManagerExternalStateMongod::remove(
            const NamespaceString& collectionName,
            const BSONObj& query,
            const BSONObj& writeConcern,
            int* numRemoved) {
        try {
            DBDirectClient client;
            client.remove(collectionName, query);

            // Handle write concern
            BSONObjBuilder gleBuilder;
            gleBuilder.append("getLastError", 1);
            gleBuilder.appendElements(writeConcern);
            BSONObj res;
            client.runCommand("admin", gleBuilder.done(), res);
            string errstr = client.getLastErrorString(res);
            if (!errstr.empty()) {
                return Status(ErrorCodes::UnknownError, errstr);
            }

            *numRemoved = res["n"].numberInt();
            return Status::OK();
        } catch (const DBException& e) {
            return e.toStatus();
        }
    }
开发者ID:CheRuisiBesares,项目名称:mongo,代码行数:26,代码来源:authz_manager_external_state_d.cpp

示例3: noteInCriticalSection

 static void noteInCriticalSection( WriteErrorDetail* staleError ) {
     BSONObjBuilder builder;
     if ( staleError->isErrInfoSet() )
         builder.appendElements( staleError->getErrInfo() );
     builder.append( "inCriticalSection", true );
     staleError->setErrInfo( builder.obj() );
 }
开发者ID:JunBian,项目名称:mongo,代码行数:7,代码来源:batch_executor.cpp

示例4: insert

    Status AuthzManagerExternalStateMongod::insert(
            const NamespaceString& collectionName,
            const BSONObj& document,
            const BSONObj& writeConcern) {
        try {
            DBDirectClient client;
            client.insert(collectionName, document);

            // Handle write concern
            BSONObjBuilder gleBuilder;
            gleBuilder.append("getLastError", 1);
            gleBuilder.appendElements(writeConcern);
            BSONObj res;
            client.runCommand("admin", gleBuilder.done(), res);
            string errstr = client.getLastErrorString(res);
            if (errstr.empty()) {
                return Status::OK();
            }
            if (res.hasField("code") && res["code"].Int() == ASSERT_ID_DUPKEY) {
                return Status(ErrorCodes::DuplicateKey, errstr);
            }
            return Status(ErrorCodes::UnknownError, errstr);
        } catch (const DBException& e) {
            return e.toStatus();
        }
    }
开发者ID:CheRuisiBesares,项目名称:mongo,代码行数:26,代码来源:authz_manager_external_state_d.cpp

示例5: update

    Status AuthzManagerExternalStateMongod::update(OperationContext* txn,
                                                   const NamespaceString& collectionName,
                                                   const BSONObj& query,
                                                   const BSONObj& updatePattern,
                                                   bool upsert,
                                                   bool multi,
                                                   const BSONObj& writeConcern,
                                                   int* nMatched) {
        try {
            DBDirectClient client(txn);
            client.update(collectionName, query, updatePattern, upsert, multi);

            // Handle write concern
            BSONObjBuilder gleBuilder;
            gleBuilder.append("getLastError", 1);
            gleBuilder.appendElements(writeConcern);
            BSONObj res;
            client.runCommand("admin", gleBuilder.done(), res);
            string err = client.getLastErrorString(res);
            if (!err.empty()) {
                return Status(ErrorCodes::UnknownError, err);
            }

            *nMatched = res["n"].numberInt();
            return Status::OK();
        } catch (const DBException& e) {
            return e.toStatus();
        }
    }
开发者ID:ambroff,项目名称:mongo,代码行数:29,代码来源:authz_manager_external_state_d.cpp

示例6: insert

 Status AuthzManagerExternalStateMock::insert(
         OperationContext* txn,
         const NamespaceString& collectionName,
         const BSONObj& document,
         const BSONObj&) {
     BSONObj toInsert;
     if (document["_id"].eoo()) {
         BSONObjBuilder docWithIdBuilder;
         docWithIdBuilder.append("_id", OID::gen());
         docWithIdBuilder.appendElements(document);
         toInsert = docWithIdBuilder.obj();
     }
     else {
         toInsert = document.copy();
     }
     _documents[collectionName].push_back(toInsert);
     if (_authzManager) {
         _authzManager->logOp(
                 "i",
                 collectionName.ns().c_str(),
                 toInsert,
                 NULL,
                 NULL);
     }
     return Status::OK();
 }
开发者ID:OpenOrganization007,项目名称:mongo,代码行数:26,代码来源:authz_manager_external_state_mock.cpp

示例7: current

 BSONObj IndexCursor::current() {
     // If the index is clustering, the full documenet is always stored in _currObj.
     // If the index is not clustering, _currObj starts as empty and gets filled
     // with the full document on the first call to current().
     if ( _currObj.isEmpty() ) {
         _nscannedObjects++;
         bool found = _cl->findByPK( _currPK, _currObj );
         if ( !found ) {
             // If we didn't find the associated object, we must be either:
             // - a snapshot transaction whose context deleted the current pk
             // - a read uncommitted cursor with stale data
             // In either case, we may advance and try again exactly once.
             TOKULOG(4) << "current() did not find associated object for pk " << _currPK << endl;
             advance();
             if ( ok() ) {
                 found = _cl->findByPK( _currPK, _currObj );
                 uassert( 16741, str::stream()
                             << toString() << ": could not find associated document with pk "
                             << _currPK << ", index key " << _currKey, found );
             }
         }
     }
     bool shouldAppendPK = _cl->isCapped() && cc().opSettings().shouldCappedAppendPK();
     if (shouldAppendPK) {
         BSONObjBuilder b;
         b.appendElements(_currObj);
         b.append("$_", _currPK);
         return b.obj();
     }
     return _currObj;
 }
开发者ID:igagnidz,项目名称:tokumx,代码行数:31,代码来源:indexcursor.cpp

示例8: run

bool WriteCmd::run(OperationContext* txn,
                   const string& dbName,
                   BSONObj& cmdObj,
                   int options,
                   string& errMsg,
                   BSONObjBuilder& result) {
    // Can't be run on secondaries.
    dassert(txn->writesAreReplicated());
    BatchedCommandRequest request(_writeType);
    BatchedCommandResponse response;

    if (!request.parseBSON(dbName, cmdObj, &errMsg) || !request.isValid(&errMsg)) {
        return appendCommandStatus(result, Status(ErrorCodes::FailedToParse, errMsg));
    }

    StatusWith<WriteConcernOptions> wcStatus = extractWriteConcern(cmdObj);

    if (!wcStatus.isOK()) {
        return appendCommandStatus(result, wcStatus.getStatus());
    }
    txn->setWriteConcern(wcStatus.getValue());

    WriteBatchExecutor writeBatchExecutor(
        txn, &globalOpCounters, &LastError::get(txn->getClient()));

    writeBatchExecutor.executeBatch(request, &response);

    result.appendElements(response.toBSON());
    return response.getOk();
}
开发者ID:Andiry,项目名称:mongo,代码行数:30,代码来源:write_commands.cpp

示例9: _insert

        void _insert( Request& r , DbMessage& d, ChunkManagerPtr manager ){
            
            while ( d.moreJSObjs() ){
                BSONObj o = d.nextJsObj();
                if ( ! manager->hasShardKey( o ) ){

                    bool bad = true;

                    if ( manager->getShardKey().partOfShardKey( "_id" ) ){
                        BSONObjBuilder b;
                        b.appendOID( "_id" , 0 , true );
                        b.appendElements( o );
                        o = b.obj();
                        bad = ! manager->hasShardKey( o );
                    }
                    
                    if ( bad ){
                        log() << "tried to insert object without shard key: " << r.getns() << "  " << o << endl;
                        throw UserException( 8011 , "tried to insert object without shard key" );
                    }
                    
                }
                
                ChunkPtr c = manager->findChunk( o );
                log(4) << "  server:" << c->getShard().toString() << " " << o << endl;
                insert( c->getShard() , r.getns() , o );

                r.gotInsert();
                
                c->splitIfShould( o.objsize() );
            }            
        }
开发者ID:thegoleffect,项目名称:mongo,代码行数:32,代码来源:strategy_shard.cpp

示例10: getKeys

        void getKeys(const BSONObj& obj, BSONObjSet& keys) const {
            verify(_fields.size() >= 1);

            BSONObjSet keysToAdd;
            // We output keys in the same order as the fields we index.
            for (size_t i = 0; i < _fields.size(); ++i) {
                const IndexedField &field = _fields[i];

                // First, we get the keys that this field adds.  Either they're added literally from
                // the value of the field, or they're transformed if the field is geo.
                BSONElementSet fieldElements;
                // false means Don't expand the last array, duh.
                obj.getFieldsDotted(field.name, fieldElements, false);

                BSONObjSet keysForThisField;
                if (IndexedField::GEO == field.type) {
                    getGeoKeys(fieldElements, &keysForThisField);
                } else if (IndexedField::LITERAL == field.type) {
                    getLiteralKeys(fieldElements, &keysForThisField);
                } else {
                    verify(0);
                }

                // We expect there to be _spec->_missingField() present in the keys if data is
                // missing.  So, this should be non-empty.
                verify(!keysForThisField.empty());

                // We take the Cartesian product of all of the keys.  This requires that we have
                // some keys to take the Cartesian product with.  If keysToAdd.empty(), we
                // initialize it.  
                if (keysToAdd.empty()) {
                    keysToAdd = keysForThisField;
                    continue;
                }

                BSONObjSet updatedKeysToAdd;
                for (BSONObjSet::const_iterator it = keysToAdd.begin(); it != keysToAdd.end();
                     ++it) {
                    for (BSONObjSet::const_iterator newIt = keysForThisField.begin();
                         newIt!= keysForThisField.end(); ++newIt) {
                        BSONObjBuilder b;
                        b.appendElements(*it);
                        b.append(newIt->firstElement());
                        updatedKeysToAdd.insert(b.obj());
                    }
                }
                keysToAdd = updatedKeysToAdd;
            }

            if (keysToAdd.size() > _params.maxKeysPerInsert) {
                warning() << "insert of geo object generated lots of keys (" << keysToAdd.size()
                          << ") consider creating larger buckets. obj="
                          << obj;
            }

            for (BSONObjSet::const_iterator it = keysToAdd.begin(); it != keysToAdd.end(); ++it) {
                keys.insert(*it);
            }
        }
开发者ID:ahopedog,项目名称:mongo,代码行数:59,代码来源:s2index.cpp

示例11:

// static
StatusWith<BSONObj> S2AccessMethod::fixSpec(const BSONObj& specObj) {
    // If the spec object has the field "2dsphereIndexVersion", validate it.  If it doesn't, add
    // {2dsphereIndexVersion: 3}, which is the default for newly-built indexes.

    BSONElement indexVersionElt = specObj[kIndexVersionFieldName];
    if (indexVersionElt.eoo()) {
        BSONObjBuilder bob;
        bob.appendElements(specObj);
        bob.append(kIndexVersionFieldName, S2_INDEX_VERSION_3);
        return bob.obj();
    }

    if (!indexVersionElt.isNumber()) {
        return {ErrorCodes::CannotCreateIndex,
                str::stream() << "Invalid type for geo index version { " << kIndexVersionFieldName
                              << " : "
                              << indexVersionElt
                              << " }, only versions: ["
                              << S2_INDEX_VERSION_1
                              << ","
                              << S2_INDEX_VERSION_2
                              << ","
                              << S2_INDEX_VERSION_3
                              << "] are supported"};
    }

    if (indexVersionElt.type() == BSONType::NumberDouble &&
        !std::isnormal(indexVersionElt.numberDouble())) {
        return {ErrorCodes::CannotCreateIndex,
                str::stream() << "Invalid value for geo index version { " << kIndexVersionFieldName
                              << " : "
                              << indexVersionElt
                              << " }, only versions: ["
                              << S2_INDEX_VERSION_1
                              << ","
                              << S2_INDEX_VERSION_2
                              << ","
                              << S2_INDEX_VERSION_3
                              << "] are supported"};
    }

    const auto indexVersion = indexVersionElt.numberLong();
    if (indexVersion != S2_INDEX_VERSION_1 && indexVersion != S2_INDEX_VERSION_2 &&
        indexVersion != S2_INDEX_VERSION_3) {
        return {ErrorCodes::CannotCreateIndex,
                str::stream() << "unsupported geo index version { " << kIndexVersionFieldName
                              << " : "
                              << indexVersionElt
                              << " }, only versions: ["
                              << S2_INDEX_VERSION_1
                              << ","
                              << S2_INDEX_VERSION_2
                              << ","
                              << S2_INDEX_VERSION_3
                              << "] are supported"};
    }

    return specObj;
}
开发者ID:Tsmith5151,项目名称:mongo,代码行数:60,代码来源:s2_access_method.cpp

示例12: passthrough

 bool passthrough( DBConfig * conf, const BSONObj& cmdObj , BSONObjBuilder& result ){
     ScopedDbConnection conn( conf->getPrimary() );
     BSONObj res;
     bool ok = conn->runCommand( conf->getName() , cmdObj , res );
     result.appendElements( res );
     conn.done();
     return ok;
 }
开发者ID:catap,项目名称:mongo,代码行数:8,代码来源:commands_public.cpp

示例13: LOG

// Make the object that describes all keys that are within our current search annulus.
BSONObj S2NearIndexCursor::makeFRSObject() {
    BSONObjBuilder frsObjBuilder;
    frsObjBuilder.appendElements(_filteredQuery);

    S2RegionCoverer coverer;
    // Step 1: Make the BSON'd covering for our search annulus.
    BSONObj inExpr;
    // Caps are inclusive and inverting a cap includes the border.  This means that our
    // initial _innerRadius of 0 is OK -- we'll still find a point that is exactly at
    // the start of our search.
    _innerCap = S2Cap::FromAxisAngle(_nearQuery.centroid,
                                     S1Angle::Radians(_innerRadius / _params.radius));
    _outerCap = S2Cap::FromAxisAngle(_nearQuery.centroid,
                                     S1Angle::Radians(_outerRadius / _params.radius));
    double area = _outerCap.area() - _innerCap.area();
    _innerCap = _innerCap.Complement();
    vector<S2Region*> regions;
    regions.push_back(&_innerCap);
    regions.push_back(&_outerCap);
    _annulus.Release(NULL);
    _annulus.Init(&regions);
    vector<S2CellId> cover;
    S2SearchUtil::setCoverLimitsBasedOnArea(area, &coverer, _params.coarsestIndexedLevel);
    coverer.GetCovering(_annulus, &cover);
    LOG(2) << "annulus cover size is " << cover.size()
           << ", params (" << coverer.min_level() << ", " << coverer.max_level() << ")"
           << endl;
    inExpr = S2SearchUtil::coverAsBSON(cover, _nearQuery.field,
                                       _params.coarsestIndexedLevel);
    frsObjBuilder.appendElements(inExpr);

    _params.configureCoverer(&coverer);
    // Cover the indexed geo components of the query.
    for (size_t i = 0; i < _indexedGeoFields.size(); ++i) {
        vector<S2CellId> cover;
        coverer.GetCovering(_indexedGeoFields[i].getRegion(), &cover);
        uassert(16761, "Couldn't generate index keys for geo field "
                + _indexedGeoFields[i].getField(),
                cover.size() > 0);
        BSONObj fieldRange = S2SearchUtil::coverAsBSON(cover, _indexedGeoFields[i].getField(),
                             _params.coarsestIndexedLevel);
        frsObjBuilder.appendElements(fieldRange);
    }

    return frsObjBuilder.obj();
}
开发者ID:p3we,项目名称:mongo,代码行数:47,代码来源:s2_near_cursor.cpp

示例14: run

        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);
        }
开发者ID:3rf,项目名称:mongo,代码行数:58,代码来源:replset_commands.cpp

示例15: _ensureId

    BSONObj InsertWriteOperation::_ensureId(const BSONObj& doc) {
        if (doc.hasField("_id"))
            return doc;

        BSONObjBuilder bob;
        bob.append("_id", OID::gen());
        bob.appendElements(doc);
        return bob.obj();
    }
开发者ID:JacketWoo,项目名称:mongosync,代码行数:9,代码来源:insert_write_operation.cpp


注:本文中的BSONObjBuilder::appendElements方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。