本文整理汇总了C++中BSONObj::getObjectField方法的典型用法代码示例。如果您正苦于以下问题:C++ BSONObj::getObjectField方法的具体用法?C++ BSONObj::getObjectField怎么用?C++ BSONObj::getObjectField使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BSONObj
的用法示例。
在下文中一共展示了BSONObj::getObjectField方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: runCount
/* { count: "collectionname"[, query: <query>] }
returns -1 on ns does not exist error.
*/
long long runCount( const char *ns, const BSONObj &cmd, string &err ) {
NamespaceDetails *d = nsdetails( ns );
if ( !d ) {
err = "ns missing";
return -1;
}
BSONObj query = cmd.getObjectField("query");
// count of all objects
if ( query.isEmpty() ){
long long num = d->nrecords;
num = num - cmd["skip"].numberLong();
if ( num < 0 ) {
num = 0;
}
if ( cmd["limit"].isNumber() ){
long long limit = cmd["limit"].numberLong();
if ( limit < num ){
num = limit;
}
}
return num;
}
QueryPlanSet qps( ns, query, BSONObj() );
CountOp original( cmd );
shared_ptr< CountOp > res = qps.runOp( original );
if ( !res->complete() ) {
log() << "Count with ns: " << ns << " and query: " << query
<< " failed with exception: " << res->exceptionMessage()
<< endl;
return 0;
}
return res->count();
}
示例2: pickSplitVector
void Chunk::pickSplitVector(vector<BSONObj>& splitPoints,
long long chunkSize /* bytes */,
int maxPoints,
int maxObjs) const {
// Ask the mongod holding this chunk to figure out the split points.
ScopedDbConnection conn(getShard().getConnString());
BSONObj result;
BSONObjBuilder cmd;
cmd.append( "splitVector" , _manager->getns() );
cmd.append( "keyPattern" , _manager->getShardKeyPattern().toBSON() );
cmd.append( "min" , getMin() );
cmd.append( "max" , getMax() );
cmd.append( "maxChunkSizeBytes" , chunkSize );
cmd.append( "maxSplitPoints" , maxPoints );
cmd.append( "maxChunkObjects" , maxObjs );
BSONObj cmdObj = cmd.obj();
if ( ! conn->runCommand( "admin" , cmdObj , result )) {
conn.done();
ostringstream os;
os << "splitVector command failed: " << result;
uassert( 13345 , os.str() , 0 );
}
BSONObjIterator it( result.getObjectField( "splitKeys" ) );
while ( it.more() ) {
splitPoints.push_back( it.next().Obj().getOwned() );
}
conn.done();
}
示例3: getMissingField
// static
BSONObj IndexLegacy::getMissingField(Collection* collection, const BSONObj& infoObj) {
BSONObj keyPattern = infoObj.getObjectField( "key" );
string accessMethodName;
if ( collection )
accessMethodName = collection->getIndexCatalog()->getAccessMethodName(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();
}
}
示例4: getMissingDoc
BSONObj Sync::getMissingDoc(const BSONObj& o) {
OplogReader missingObjReader;
const char *ns = o.getStringField("ns");
// capped collections
NamespaceDetails *nsd = nsdetails(ns);
if ( nsd && nsd->isCapped() ) {
log() << "replication missing doc, but this is okay for a capped collection (" << ns << ")" << endl;
return BSONObj();
}
uassert(15916, str::stream() << "Can no longer connect to initial sync source: " << hn, missingObjReader.connect(hn));
// might be more than just _id in the update criteria
BSONObj query = BSONObjBuilder().append(o.getObjectField("o2")["_id"]).obj();
BSONObj missingObj;
try {
missingObj = missingObjReader.findOne(ns, query);
} catch(DBException& e) {
log() << "replication assertion fetching missing object: " << e.what() << endl;
throw;
}
return missingObj;
}
示例5: addRequiredPrivileges
void Pipeline::addRequiredPrivileges(const string& db,
BSONObj cmdObj,
vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::find);
out->push_back(Privilege(db + '.' + cmdObj.firstElement().str(), actions));
if (false && cmdObj["allowDiskUsage"].trueValue()) {
// TODO no privilege for this yet.
}
BSONObj pipeline = cmdObj.getObjectField("pipeline");
BSONForEach(stageElem, pipeline) {
BSONObj stage = stageElem.embeddedObjectUserCheck();
if (str::equals(stage.firstElementFieldName(), "$out")) {
// TODO Figure out how to handle temp collection privileges. For now, using the
// output ns is ok since we only do db-level privilege checks.
const string outputNs = db + '.' + stage.firstElement().str();
ActionSet actions;
// logically on output ns
actions.addAction(ActionType::remove);
actions.addAction(ActionType::insert);
actions.addAction(ActionType::indexRead);
// on temp ns due to implementation, but not logically on output ns
actions.addAction(ActionType::createCollection);
actions.addAction(ActionType::ensureIndex);
actions.addAction(ActionType::dropCollection);
actions.addAction(ActionType::renameCollectionSameDB);
out->push_back(Privilege(outputNs, actions));
}
}
示例6: getMissingDoc
BSONObj SyncTail::getMissingDoc(OperationContext* txn, Database* db, const BSONObj& o) {
OplogReader missingObjReader; // why are we using OplogReader to run a non-oplog query?
const char* ns = o.getStringField("ns");
// capped collections
Collection* collection = db->getCollection(ns);
if (collection && collection->isCapped()) {
log() << "missing doc, but this is okay for a capped collection (" << ns << ")";
return BSONObj();
}
const int retryMax = 3;
for (int retryCount = 1; retryCount <= retryMax; ++retryCount) {
if (retryCount != 1) {
// if we are retrying, sleep a bit to let the network possibly recover
sleepsecs(retryCount * retryCount);
}
try {
bool ok = missingObjReader.connect(HostAndPort(_hostname));
if (!ok) {
warning() << "network problem detected while connecting to the "
<< "sync source, attempt " << retryCount << " of " << retryMax << endl;
continue; // try again
}
} catch (const SocketException&) {
warning() << "network problem detected while connecting to the "
<< "sync source, attempt " << retryCount << " of " << retryMax << endl;
continue; // try again
}
// get _id from oplog entry to create query to fetch document.
const BSONElement opElem = o.getField("op");
const bool isUpdate = !opElem.eoo() && opElem.str() == "u";
const BSONElement idElem = o.getObjectField(isUpdate ? "o2" : "o")["_id"];
if (idElem.eoo()) {
severe() << "cannot fetch missing document without _id field: " << o.toString();
fassertFailedNoTrace(28742);
}
BSONObj query = BSONObjBuilder().append(idElem).obj();
BSONObj missingObj;
try {
missingObj = missingObjReader.findOne(ns, query);
} catch (const SocketException&) {
warning() << "network problem detected while fetching a missing document from the "
<< "sync source, attempt " << retryCount << " of " << retryMax << endl;
continue; // try again
} catch (DBException& e) {
error() << "assertion fetching missing object: " << e.what() << endl;
throw;
}
// success!
return missingObj;
}
// retry count exceeded
msgasserted(15916,
str::stream() << "Can no longer connect to initial sync source: " << _hostname);
}
示例7: run
virtual bool run(const char *ns, BSONObj& cmdObj, string& errmsg, BSONObjBuilder& result, bool fromRepl) {
string fromhost = cmdObj.getStringField("from");
if ( fromhost.empty() ) {
errmsg = "missing from spec";
return false;
}
string collection = cmdObj.getStringField("cloneCollection");
if ( collection.empty() ) {
errmsg = "missing cloneCollection spec";
return false;
}
BSONObj query = cmdObj.getObjectField("query");
if ( query.isEmpty() )
query = BSONObj();
BSONElement copyIndexesSpec = cmdObj.getField("copyindexes");
bool copyIndexes = copyIndexesSpec.isBoolean() ? copyIndexesSpec.boolean() : true;
// Will not be used if doesn't exist.
int logSizeMb = cmdObj.getIntField( "logSizeMb" );
/* replication note: we must logOp() not the command, but the cloned data -- if the slave
were to clone it would get a different point-in-time and not match.
*/
setClient( collection.c_str() );
log() << "cloneCollection. db:" << ns << " collection:" << collection << " from: " << fromhost << " query: " << query << ( copyIndexes ? "" : ", not copying indexes" ) << endl;
Cloner c;
long long cursorId;
if ( !c.startCloneCollection( fromhost.c_str(), collection.c_str(), query, errmsg, !fromRepl, copyIndexes, logSizeMb, cursorId ) )
return false;
return c.finishCloneCollection( fromhost.c_str(), collection.c_str(), query, cursorId, errmsg);
}
示例8: prepareToBuildIndex
bool prepareToBuildIndex(const BSONObj& io,
bool mayInterrupt,
bool god,
const string& sourceNS ) {
BSONObj key = io.getObjectField("key");
/* this is because we want key patterns like { _id : 1 } and { _id : <someobjid> } to
all be treated as the same pattern.
*/
if ( IndexDetails::isIdIndexPattern(key) ) {
if( !god ) {
ensureHaveIdIndex( sourceNS.c_str(), mayInterrupt );
return false;
}
}
else {
/* is buildIndexes:false set for this replica set member?
if so we don't build any indexes except _id
*/
if( theReplSet && !theReplSet->buildIndexes() )
return false;
}
string pluginName = IndexNames::findPluginName( key );
if ( pluginName.size() ) {
if (needToUpgradeMinorVersion(pluginName))
upgradeMinorVersionOrAssert(pluginName);
}
return true;
}
示例9: addRequiredPrivileges
void Pipeline::addRequiredPrivileges(Command* commandTemplate,
const string& db,
BSONObj cmdObj,
vector<Privilege>* out) {
ResourcePattern inputResource(commandTemplate->parseResourcePattern(db, cmdObj));
uassert(17138,
mongoutils::str::stream() << "Invalid input resource, " << inputResource.toString(),
inputResource.isExactNamespacePattern());
if (false && cmdObj["allowDiskUsage"].trueValue()) {
// TODO no privilege for this yet.
}
out->push_back(Privilege(inputResource, ActionType::find));
BSONObj pipeline = cmdObj.getObjectField("pipeline");
BSONForEach(stageElem, pipeline) {
BSONObj stage = stageElem.embeddedObjectUserCheck();
if (str::equals(stage.firstElementFieldName(), "$out")) {
NamespaceString outputNs(db, stage.firstElement().str());
uassert(17139,
mongoutils::str::stream() << "Invalid $out target namespace, " <<
outputNs.ns(),
outputNs.isValid());
ActionSet actions;
actions.addAction(ActionType::remove);
actions.addAction(ActionType::insert);
out->push_back(Privilege(ResourcePattern::forExactNamespace(outputNs), actions));
}
}
示例10: upgradeMinorVersionOrAssert
static void upgradeMinorVersionOrAssert(const string& newPluginName) {
const string systemIndexes = cc().database()->name() + ".system.indexes";
auto_ptr<Runner> runner(InternalPlanner::collectionScan(systemIndexes));
BSONObj index;
Runner::RunnerState state;
while (Runner::RUNNER_ADVANCED == (state = runner->getNext(&index, NULL))) {
const BSONObj key = index.getObjectField("key");
const string plugin = IndexNames::findPluginName(key);
if (IndexNames::existedBefore24(plugin))
continue;
const string errmsg = str::stream()
<< "Found pre-existing index " << index << " with invalid type '" << plugin << "'. "
<< "Disallowing creation of new index type '" << newPluginName << "'. See "
<< "http://dochub.mongodb.org/core/index-type-changes"
;
error() << errmsg << endl;
uasserted(16738, errmsg);
}
if (Runner::RUNNER_EOF != state) {
warning() << "Internal error while reading collection " << systemIndexes << endl;
}
DataFileHeader* dfh = cc().database()->getFile(0)->getHeader();
getDur().writingInt(dfh->versionMinor) = PDFILE_VERSION_MINOR_24_AND_NEWER;
}
示例11: checkAuthForCommand
Status Pipeline::checkAuthForCommand(Client* client, const std::string& db, const BSONObj& cmdObj) {
NamespaceString inputNs(db, cmdObj.firstElement().str());
auto inputResource = ResourcePattern::forExactNamespace(inputNs);
uassert(17138,
mongoutils::str::stream() << "Invalid input namespace, " << inputNs.ns(),
inputNs.isValid());
PrivilegeVector privileges;
if (dps::extractElementAtPath(cmdObj, "pipeline.0.$indexStats")) {
Privilege::addPrivilegeToPrivilegeVector(
&privileges,
Privilege(ResourcePattern::forAnyNormalResource(), ActionType::indexStats));
} else if (dps::extractElementAtPath(cmdObj, "pipeline.0.$collStats")) {
Privilege::addPrivilegeToPrivilegeVector(&privileges,
Privilege(inputResource, ActionType::collStats));
} else {
// If no source requiring an alternative permission scheme is specified then default to
// requiring find() privileges on the given namespace.
Privilege::addPrivilegeToPrivilegeVector(&privileges,
Privilege(inputResource, ActionType::find));
}
BSONObj pipeline = cmdObj.getObjectField("pipeline");
for (auto&& stageElem : pipeline) {
addPrivilegesForStage(db, cmdObj, &privileges, stageElem.embeddedObjectUserCheck());
}
if (AuthorizationSession::get(client)->isAuthorizedForPrivileges(privileges))
return Status::OK();
return Status(ErrorCodes::Unauthorized, "unauthorized");
}
示例12: pretouchOperation
void pretouchOperation(OperationContext* txn, const BSONObj& op) {
if (txn->lockState()->isWriteLocked()) {
// no point pretouching if write locked. not sure if this will ever fire, but just in case.
return;
}
const char* which = "o";
const char* opType = op.getStringField("op");
if (*opType == 'i')
;
else if (*opType == 'u')
which = "o2";
else
return;
/* todo : other operations */
try {
BSONObj o = op.getObjectField(which);
BSONElement _id;
if (o.getObjectID(_id)) {
const char* ns = op.getStringField("ns");
BSONObjBuilder b;
b.append(_id);
BSONObj result;
AutoGetCollectionForRead ctx(txn, ns);
if (Helpers::findById(txn, ctx.getDb(), ns, b.done(), result)) {
_dummy_z += result.objsize(); // touch
}
}
} catch (DBException&) {
log() << "ignoring assertion in pretouchOperation()" << endl;
}
}
示例13: pretouchOperation
void pretouchOperation(const BSONObj& op) {
if( Lock::somethingWriteLocked() )
return; // no point pretouching if write locked. not sure if this will ever fire, but just in case.
const char *which = "o";
const char *opType = op.getStringField("op");
if ( *opType == 'i' )
;
else if( *opType == 'u' )
which = "o2";
else
return;
/* todo : other operations */
try {
BSONObj o = op.getObjectField(which);
BSONElement _id;
if( o.getObjectID(_id) ) {
const char *ns = op.getStringField("ns");
BSONObjBuilder b;
b.append(_id);
BSONObj result;
Client::ReadContext ctx( ns );
if( Helpers::findById(cc(), ns, b.done(), result) )
_dummy_z += result.objsize(); // touch
}
}
catch( DBException& ) {
log() << "ignoring assertion in pretouchOperation()" << endl;
}
}
示例14: run
bool run(const char *cmdns, BSONObj& cmdObj, string& errmsg, BSONObjBuilder& result, bool){
// so i have to start clone, tell caller its ok to make change
// at this point the caller locks me, and updates config db
// then finish calls finish, and then deletes data when cursors are done
string ns = cmdObj["movechunk.start"].valuestrsafe();
string to = cmdObj["to"].valuestrsafe();
string from = cmdObj["from"].valuestrsafe(); // my public address, a tad redundant, but safe
BSONObj filter = cmdObj.getObjectField( "filter" );
if ( ns.size() == 0 ){
errmsg = "need to specify namespace in command";
return false;
}
if ( to.size() == 0 ){
errmsg = "need to specify server to move shard to";
return false;
}
if ( from.size() == 0 ){
errmsg = "need to specify server to move shard from (redundat i know)";
return false;
}
if ( filter.isEmpty() ){
errmsg = "need to specify a filter";
return false;
}
log() << "got movechunk.start: " << cmdObj << endl;
BSONObj res;
bool ok;
{
dbtemprelease unlock;
ScopedDbConnection conn( to );
ok = conn->runCommand( "admin" ,
BSON( "startCloneCollection" << ns <<
"from" << from <<
"query" << filter
) ,
res );
conn.done();
}
log() << " movechunk.start res: " << res << endl;
if ( ok ){
result.append( res["finishToken"] );
}
else {
errmsg = "startCloneCollection failed: ";
errmsg += res["errmsg"].valuestrsafe();
}
return ok;
}
示例15: parseRequest
/**
* Parses a count command object, 'cmdObj'.
*
* On success, fills in the out-parameter 'request' and returns an OK status.
*
* Returns a failure status if 'cmdObj' is not well formed.
*/
Status parseRequest(const std::string& dbname,
const BSONObj& cmdObj,
CountRequest* request) const {
long long skip = 0;
if (cmdObj["skip"].isNumber()) {
skip = cmdObj["skip"].numberLong();
if (skip < 0) {
return Status(ErrorCodes::BadValue, "skip value is negative in count query");
}
}
else if (cmdObj["skip"].ok()) {
return Status(ErrorCodes::BadValue, "skip value is not a valid number");
}
long long limit = 0;
if (cmdObj["limit"].isNumber()) {
limit = cmdObj["limit"].numberLong();
}
else if (cmdObj["limit"].ok()) {
return Status(ErrorCodes::BadValue, "limit value is not a valid number");
}
// For counts, limit and -limit mean the same thing.
if (limit < 0) {
limit = -limit;
}
// We don't validate that "query" is a nested object due to SERVER-15456.
BSONObj query = cmdObj.getObjectField("query");
BSONObj hintObj;
if (Object == cmdObj["hint"].type()) {
hintObj = cmdObj["hint"].Obj();
}
else if (String == cmdObj["hint"].type()) {
const std::string hint = cmdObj.getStringField("hint");
hintObj = BSON("$hint" << hint);
}
std::string ns = parseNs(dbname, cmdObj);
if (!nsIsFull(ns)) {
return Status(ErrorCodes::BadValue, "collection name missing");
}
// Parsed correctly. Fill out 'request' with the results.
request->ns = ns;
request->query = query;
request->hint = hintObj;
request->limit = limit;
request->skip = skip;
// By default, count requests are regular count not explain of count.
request->explain = false;
return Status::OK();
}