本文整理汇总了C++中BSONElement::numberInt方法的典型用法代码示例。如果您正苦于以下问题:C++ BSONElement::numberInt方法的具体用法?C++ BSONElement::numberInt怎么用?C++ BSONElement::numberInt使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BSONElement
的用法示例。
在下文中一共展示了BSONElement::numberInt方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: parse
Status CollectionOptions::parse(const BSONObj& options) {
reset();
// During parsing, ignore some validation errors in order to accept options objects that
// were valid in previous versions of the server. SERVER-13737.
BSONObjIterator i( options );
while ( i.more() ) {
BSONElement e = i.next();
StringData fieldName = e.fieldName();
if ( fieldName == "capped" ) {
capped = e.trueValue();
}
else if ( fieldName == "size" ) {
if ( !e.isNumber() ) {
// Ignoring for backwards compatibility.
continue;
}
cappedSize = e.numberLong();
if ( cappedSize < 0 )
return Status( ErrorCodes::BadValue, "size has to be >= 0" );
cappedSize += 0xff;
cappedSize &= 0xffffffffffffff00LL;
}
else if ( fieldName == "max" ) {
if ( !options["capped"].trueValue() || !e.isNumber() ) {
// Ignoring for backwards compatibility.
continue;
}
cappedMaxDocs = e.numberLong();
if ( !validMaxCappedDocs( &cappedMaxDocs ) )
return Status( ErrorCodes::BadValue,
"max in a capped collection has to be < 2^31 or not set" );
}
else if ( fieldName == "$nExtents" ) {
if ( e.type() == Array ) {
BSONObjIterator j( e.Obj() );
while ( j.more() ) {
BSONElement inner = j.next();
initialExtentSizes.push_back( inner.numberInt() );
}
}
else {
initialNumExtents = e.numberLong();
}
}
else if ( fieldName == "autoIndexId" ) {
if ( e.trueValue() )
autoIndexId = YES;
else
autoIndexId = NO;
}
else if ( fieldName == "flags" ) {
flags = e.numberInt();
flagsSet = true;
}
else if ( fieldName == "temp" ) {
temp = e.trueValue();
}
else if (fieldName == "storageEngine") {
// Storage engine-specific collection options.
// "storageEngine" field must be of type "document".
// Every field inside "storageEngine" has to be a document.
// Format:
// {
// ...
// storageEngine: {
// storageEngine1: {
// ...
// },
// storageEngine2: {
// ...
// }
// },
// ...
// }
if (e.type() != mongo::Object) {
return Status(ErrorCodes::BadValue, "'storageEngine' has to be a document.");
}
BSONObjIterator j(e.Obj());
if (!j.more()) {
return Status(ErrorCodes::BadValue,
"Empty 'storageEngine' options are invalid. "
"Please remove, or include valid options.");
}
// Loop through each provided storageEngine.
while (j.more()) {
BSONElement storageEngineElement = j.next();
StringData storageEngineName = storageEngineElement.fieldNameStringData();
if (storageEngineElement.type() != mongo::Object) {
return Status(ErrorCodes::BadValue, str::stream() << "'storageEngine." <<
storageEngineName << "' has to be an embedded document.");
}
}
storageEngine = e.Obj().getOwned();
}
}
//.........这里部分代码省略.........
示例2: solutionMatches
// static
bool QueryPlannerTestLib::solutionMatches(const BSONObj& testSoln,
const QuerySolutionNode* trueSoln) {
//
// leaf nodes
//
if (STAGE_COLLSCAN == trueSoln->getType()) {
const CollectionScanNode* csn = static_cast<const CollectionScanNode*>(trueSoln);
BSONElement el = testSoln["cscan"];
if (el.eoo() || !el.isABSONObj()) {
return false;
}
BSONObj csObj = el.Obj();
BSONElement dir = csObj["dir"];
if (dir.eoo() || !dir.isNumber()) {
return false;
}
if (dir.numberInt() != csn->direction) {
return false;
}
BSONElement filter = csObj["filter"];
if (filter.eoo()) {
return true;
} else if (filter.isNull()) {
return NULL == csn->filter;
} else if (!filter.isABSONObj()) {
return false;
}
BSONObj collation;
if (BSONElement collationElt = csObj["collation"]) {
if (!collationElt.isABSONObj()) {
return false;
}
collation = collationElt.Obj();
}
return filterMatches(filter.Obj(), collation, trueSoln);
} else if (STAGE_IXSCAN == trueSoln->getType()) {
const IndexScanNode* ixn = static_cast<const IndexScanNode*>(trueSoln);
BSONElement el = testSoln["ixscan"];
if (el.eoo() || !el.isABSONObj()) {
return false;
}
BSONObj ixscanObj = el.Obj();
BSONElement pattern = ixscanObj["pattern"];
if (!pattern.eoo()) {
if (!pattern.isABSONObj()) {
return false;
}
if (pattern.Obj() != ixn->index.keyPattern) {
return false;
}
}
BSONElement name = ixscanObj["name"];
if (!name.eoo()) {
if (name.type() != BSONType::String) {
return false;
}
if (name.valueStringData() != ixn->index.name) {
return false;
}
}
if (name.eoo() && pattern.eoo()) {
return false;
}
BSONElement bounds = ixscanObj["bounds"];
if (!bounds.eoo()) {
if (!bounds.isABSONObj()) {
return false;
} else if (!boundsMatch(bounds.Obj(), ixn->bounds)) {
return false;
}
}
BSONElement dir = ixscanObj["dir"];
if (!dir.eoo() && NumberInt == dir.type()) {
if (dir.numberInt() != ixn->direction) {
return false;
}
}
BSONElement filter = ixscanObj["filter"];
if (filter.eoo()) {
return true;
} else if (filter.isNull()) {
return NULL == ixn->filter;
} else if (!filter.isABSONObj()) {
return false;
}
BSONObj collation;
if (BSONElement collationElt = ixscanObj["collation"]) {
if (!collationElt.isABSONObj()) {
//.........这里部分代码省略.........
示例3: run
bool run(const string& dbname, BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool fromRepl ) {
int s = 0;
bool found = setParmsMongodSpecific(dbname, cmdObj, errmsg, result, fromRepl);
if( cmdObj.hasElement("journalCommitInterval") ) {
if( !cmdLine.dur ) {
errmsg = "journaling is off";
return false;
}
int x = (int) cmdObj["journalCommitInterval"].Number();
verify( x > 1 && x < 500 );
cmdLine.journalCommitInterval = x;
log() << "setParameter journalCommitInterval=" << x << endl;
s++;
}
if( cmdObj.hasElement("notablescan") ) {
verify( !cmdLine.isMongos() );
if( s == 0 )
result.append("was", cmdLine.noTableScan);
cmdLine.noTableScan = cmdObj["notablescan"].Bool();
s++;
}
if( cmdObj.hasElement("quiet") ) {
if( s == 0 )
result.append("was", cmdLine.quiet );
cmdLine.quiet = cmdObj["quiet"].Bool();
s++;
}
if( cmdObj.hasElement("syncdelay") ) {
verify( !cmdLine.isMongos() );
if( s == 0 )
result.append("was", cmdLine.syncdelay );
cmdLine.syncdelay = cmdObj["syncdelay"].Number();
s++;
}
if( cmdObj.hasElement( "logLevel" ) ) {
if( s == 0 )
result.append("was", logLevel );
logLevel = cmdObj["logLevel"].numberInt();
s++;
}
if( cmdObj.hasElement( "replApplyBatchSize" ) ) {
if( s == 0 )
result.append("was", replApplyBatchSize );
BSONElement e = cmdObj["replApplyBatchSize"];
ParameterValidator * v = ParameterValidator::get( e.fieldName() );
verify( v );
if ( ! v->isValid( e , errmsg ) )
return false;
replApplyBatchSize = e.numberInt();
s++;
}
if( cmdObj.hasElement( "traceExceptions" ) ) {
if( s == 0 ) result.append( "was", DBException::traceExceptions );
DBException::traceExceptions = cmdObj["traceExceptions"].Bool();
s++;
}
if( cmdObj.hasElement( "replMonitorMaxFailedChecks" ) ) {
if( s == 0 ) result.append( "was", ReplicaSetMonitor::getMaxFailedChecks() );
ReplicaSetMonitor::setMaxFailedChecks(
cmdObj["replMonitorMaxFailedChecks"].numberInt() );
s++;
}
if( s == 0 && !found ) {
errmsg = "no option found to set, use help:true to see options ";
return false;
}
return true;
}
示例4: computeProperties
void IndexScanNode::computeProperties() {
_sorts.clear();
BSONObj sortPattern;
{
BSONObjBuilder sortBob;
BSONObj normalizedIndexKeyPattern(LiteParsedQuery::normalizeSortOrder(indexKeyPattern));
BSONObjIterator it(normalizedIndexKeyPattern);
while (it.more()) {
BSONElement elt = it.next();
// Zero is returned if elt is not a number. This happens when elt is hashed or
// 2dsphere, our two projection indices. We want to drop those from the sort
// pattern.
int val = elt.numberInt() * direction;
if (0 != val) {
sortBob.append(elt.fieldName(), val);
}
}
sortPattern = sortBob.obj();
}
_sorts.insert(sortPattern);
const int nFields = sortPattern.nFields();
if (nFields > 1) {
// We're sorted not only by sortPattern but also by all prefixes of it.
for (int i = 0; i < nFields; ++i) {
// Make obj out of fields [0,i]
BSONObjIterator it(sortPattern);
BSONObjBuilder prefixBob;
for (int j = 0; j <= i; ++j) {
prefixBob.append(it.next());
}
_sorts.insert(prefixBob.obj());
}
}
// If we are using the index {a:1, b:1} to answer the predicate {a: 10}, it's sorted
// both by the index key pattern and by the pattern {b: 1}.
// See if there are any fields with equalities for bounds. We can drop these
// from any sort orders created.
set<string> equalityFields;
if (!bounds.isSimpleRange) {
// Figure out how many fields are point intervals.
for (size_t i = 0; i < bounds.fields.size(); ++i) {
const OrderedIntervalList& oil = bounds.fields[i];
if (oil.intervals.size() != 1) {
continue;
}
const Interval& ival = oil.intervals[0];
if (!ival.isPoint()) {
continue;
}
equalityFields.insert(oil.name);
}
}
if (equalityFields.empty()) {
return;
}
// TODO: Each field in equalityFields could be dropped from the sort order since it is
// a point interval. The full set of sort orders is as follows:
// For each sort in _sorts:
// For each drop in powerset(equalityFields):
// Remove fields in 'drop' from 'sort' and add resulting sort to output.
// Since this involves a powerset, we only remove point intervals that the prior sort
// planning code removed, namely the contiguous prefix of the key pattern.
BSONObjIterator it(sortPattern);
BSONObjBuilder prefixBob;
while (it.more()) {
BSONElement elt = it.next();
// XXX string slowness. fix when bounds are stringdata not string.
if (equalityFields.end() == equalityFields.find(string(elt.fieldName()))) {
prefixBob.append(elt);
// This field isn't a point interval, can't drop.
break;
}
}
while (it.more()) {
prefixBob.append(it.next());
}
// If we have an index {a:1} and an equality on 'a' don't append an empty sort order.
BSONObj filterPointsObj = prefixBob.obj();
if (!filterPointsObj.isEmpty()) {
_sorts.insert(filterPointsObj);
}
}
示例5: i
StatusWith<BSONObj> FTSSpec::fixSpec(const BSONObj& spec) {
if (spec["textIndexVersion"].numberInt() == TEXT_INDEX_VERSION_1) {
return _fixSpecV1(spec);
}
map<string, int> m;
BSONObj keyPattern;
{
BSONObjBuilder b;
// Populate m and keyPattern.
{
bool addedFtsStuff = false;
BSONObjIterator i(spec["key"].Obj());
while (i.more()) {
BSONElement e = i.next();
if (e.fieldNameStringData() == "_fts") {
if (INDEX_NAME != e.valuestrsafe()) {
return {ErrorCodes::CannotCreateIndex, "expecting _fts:\"text\""};
}
addedFtsStuff = true;
b.append(e);
} else if (e.fieldNameStringData() == "_ftsx") {
if (e.numberInt() != 1) {
return {ErrorCodes::CannotCreateIndex, "expecting _ftsx:1"};
}
b.append(e);
} else if (e.type() == String && INDEX_NAME == e.valuestr()) {
if (!addedFtsStuff) {
_addFTSStuff(&b);
addedFtsStuff = true;
}
m[e.fieldName()] = 1;
} else {
if (e.numberInt() != 1 && e.numberInt() != -1) {
return {ErrorCodes::CannotCreateIndex,
"expected value 1 or -1 for non-text key in compound index"};
}
b.append(e);
}
}
verify(addedFtsStuff);
}
keyPattern = b.obj();
// Verify that index key is in the correct format: extraBefore fields, then text
// fields, then extraAfter fields.
{
BSONObjIterator i(spec["key"].Obj());
verify(i.more());
BSONElement e = i.next();
// extraBefore fields
while (String != e.type()) {
Status notReservedStatus = verifyFieldNameNotReserved(e.fieldNameStringData());
if (!notReservedStatus.isOK()) {
return notReservedStatus;
}
if (!i.more()) {
return {ErrorCodes::CannotCreateIndex,
"expected additional fields in text index key pattern"};
}
e = i.next();
}
// text fields
bool alreadyFixed = (e.fieldNameStringData() == "_fts");
if (alreadyFixed) {
if (!i.more()) {
return {ErrorCodes::CannotCreateIndex, "expected _ftsx after _fts"};
}
e = i.next();
if (e.fieldNameStringData() != "_ftsx") {
return {ErrorCodes::CannotCreateIndex, "expected _ftsx after _fts"};
}
e = i.next();
} else {
do {
Status notReservedStatus = verifyFieldNameNotReserved(e.fieldNameStringData());
if (!notReservedStatus.isOK()) {
return notReservedStatus;
}
e = i.next();
} while (!e.eoo() && e.type() == String);
}
// extraAfterFields
while (!e.eoo()) {
if (e.type() == BSONType::String) {
return {ErrorCodes::CannotCreateIndex,
"'text' fields in index must all be adjacent"};
}
Status notReservedStatus = verifyFieldNameNotReserved(e.fieldNameStringData());
if (!notReservedStatus.isOK()) {
return notReservedStatus;
}
//.........这里部分代码省略.........
示例6: handleSpecialNamespaces
bool handleSpecialNamespaces( Request& r , QueryMessage& q ) {
const char * ns = strstr( r.getns() , ".$cmd.sys." );
if ( ! ns )
return false;
ns += 10;
BSONObjBuilder b;
vector<Shard> shards;
ClientBasic* client = ClientBasic::getCurrent();
AuthorizationSession* authSession = client->getAuthorizationSession();
if ( strcmp( ns , "inprog" ) == 0 ) {
const bool isAuthorized = authSession->isAuthorizedForActionsOnResource(
ResourcePattern::forClusterResource(), ActionType::inprog);
audit::logInProgAuthzCheck(
client, q.query, isAuthorized ? ErrorCodes::OK : ErrorCodes::Unauthorized);
uassert(ErrorCodes::Unauthorized, "not authorized to run inprog", isAuthorized);
Shard::getAllShards( shards );
BSONArrayBuilder arr( b.subarrayStart( "inprog" ) );
for ( unsigned i=0; i<shards.size(); i++ ) {
Shard shard = shards[i];
ScopedDbConnection conn(shard.getConnString());
BSONObj temp = conn->findOne( r.getns() , q.query );
if ( temp["inprog"].isABSONObj() ) {
BSONObjIterator i( temp["inprog"].Obj() );
while ( i.more() ) {
BSONObjBuilder x;
BSONObjIterator j( i.next().Obj() );
while( j.more() ) {
BSONElement e = j.next();
if ( str::equals( e.fieldName() , "opid" ) ) {
stringstream ss;
ss << shard.getName() << ':' << e.numberInt();
x.append( "opid" , ss.str() );
}
else if ( str::equals( e.fieldName() , "client" ) ) {
x.appendAs( e , "client_s" );
}
else {
x.append( e );
}
}
arr.append( x.obj() );
}
}
conn.done();
}
arr.done();
}
else if ( strcmp( ns , "killop" ) == 0 ) {
const bool isAuthorized = authSession->isAuthorizedForActionsOnResource(
ResourcePattern::forClusterResource(), ActionType::killop);
audit::logKillOpAuthzCheck(
client,
q.query,
isAuthorized ? ErrorCodes::OK : ErrorCodes::Unauthorized);
uassert(ErrorCodes::Unauthorized, "not authorized to run killop", isAuthorized);
BSONElement e = q.query["op"];
if ( e.type() != String ) {
b.append( "err" , "bad op" );
b.append( e );
}
else {
b.append( e );
string s = e.String();
string::size_type i = s.find( ':' );
if ( i == string::npos ) {
b.append( "err" , "bad opid" );
}
else {
string shard = s.substr( 0 , i );
int opid = atoi( s.substr( i + 1 ).c_str() );
b.append( "shard" , shard );
b.append( "shardid" , opid );
log() << "want to kill op: " << e << endl;
Shard s(shard);
ScopedDbConnection conn(s.getConnString());
conn->findOne( r.getns() , BSON( "op" << opid ) );
conn.done();
}
}
}
else if ( strcmp( ns , "unlock" ) == 0 ) {
b.append( "err" , "can't do unlock through mongos" );
}
else {
warning() << "unknown sys command [" << ns << "]" << endl;
return false;
}
BSONObj x = b.done();
replyToQuery(0, r.p(), r.m(), x);
//.........这里部分代码省略.........
示例7: run
bool run(const string& dbname, BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool fromRepl) {
string ns = dbname + "." + cmdObj.firstElement().valuestr();
if (!cmdObj["start"].eoo()) {
errmsg = "using deprecated 'start' argument to geoNear";
return false;
}
Database* db = cc().database();
if ( !db ) {
errmsg = "can't find ns";
return false;
}
Collection* collection = db->getCollection( ns );
if ( !collection ) {
errmsg = "can't find ns";
return false;
}
IndexCatalog* indexCatalog = collection->getIndexCatalog();
// cout << "raw cmd " << cmdObj.toString() << endl;
// We seek to populate this.
string nearFieldName;
bool using2DIndex = false;
if (!getFieldName(collection, indexCatalog, &nearFieldName, &errmsg, &using2DIndex)) {
return false;
}
uassert(17304, "'near' field must be point",
!cmdObj["near"].eoo() && cmdObj["near"].isABSONObj()
&& GeoParser::isPoint(cmdObj["near"].Obj()));
bool isSpherical = cmdObj["spherical"].trueValue();
if (!using2DIndex) {
uassert(17301, "2dsphere index must have spherical: true", isSpherical);
}
// Build the $near expression for the query.
BSONObjBuilder nearBob;
if (isSpherical) {
nearBob.append("$nearSphere", cmdObj["near"].Obj());
}
else {
nearBob.append("$near", cmdObj["near"].Obj());
}
if (!cmdObj["maxDistance"].eoo()) {
uassert(17299, "maxDistance must be a number",cmdObj["maxDistance"].isNumber());
nearBob.append("$maxDistance", cmdObj["maxDistance"].number());
}
if (!cmdObj["minDistance"].eoo()) {
uassert(17298, "minDistance doesn't work on 2d index", !using2DIndex);
uassert(17300, "minDistance must be a number",cmdObj["minDistance"].isNumber());
nearBob.append("$minDistance", cmdObj["minDistance"].number());
}
if (!cmdObj["uniqueDocs"].eoo()) {
nearBob.append("$uniqueDocs", cmdObj["uniqueDocs"].trueValue());
}
// And, build the full query expression.
BSONObjBuilder queryBob;
queryBob.append(nearFieldName, nearBob.obj());
if (!cmdObj["query"].eoo() && cmdObj["query"].isABSONObj()) {
queryBob.appendElements(cmdObj["query"].Obj());
}
BSONObj rewritten = queryBob.obj();
// cout << "rewritten query: " << rewritten.toString() << endl;
int numWanted = 100;
const char* limitName = !cmdObj["num"].eoo() ? "num" : "limit";
BSONElement eNumWanted = cmdObj[limitName];
if (!eNumWanted.eoo()) {
uassert(17303, "limit must be number", eNumWanted.isNumber());
numWanted = eNumWanted.numberInt();
uassert(17302, "limit must be >=0", numWanted >= 0);
}
bool includeLocs = false;
if (!cmdObj["includeLocs"].eoo()) {
includeLocs = cmdObj["includeLocs"].trueValue();
}
double distanceMultiplier = 1.0;
BSONElement eDistanceMultiplier = cmdObj["distanceMultiplier"];
if (!eDistanceMultiplier.eoo()) {
uassert(17296, "distanceMultiplier must be a number", eDistanceMultiplier.isNumber());
distanceMultiplier = eDistanceMultiplier.number();
uassert(17297, "distanceMultiplier must be non-negative", distanceMultiplier >= 0);
}
BSONObj projObj = BSON("$pt" << BSON("$meta" << LiteParsedQuery::metaGeoNearPoint) <<
"$dis" << BSON("$meta" << LiteParsedQuery::metaGeoNearDistance));
CanonicalQuery* cq;
//.........这里部分代码省略.........
示例8: _parseSettingsSubdocument
Status ReplicaSetConfig::_parseSettingsSubdocument(const BSONObj& settings) {
//
// Parse heartbeatIntervalMillis
//
long long heartbeatIntervalMillis;
Status hbIntervalStatus =
bsonExtractIntegerFieldWithDefault(settings,
kHeartbeatIntervalFieldName,
durationCount<Milliseconds>(kDefaultHeartbeatInterval),
&heartbeatIntervalMillis);
if (!hbIntervalStatus.isOK()) {
return hbIntervalStatus;
}
_heartbeatInterval = Milliseconds(heartbeatIntervalMillis);
// Parse electionTimeoutMillis
//
BSONElement electionTimeoutMillisElement = settings[kElectionTimeoutFieldName];
if (electionTimeoutMillisElement.eoo()) {
_electionTimeoutPeriod = Milliseconds(kDefaultElectionTimeoutPeriod);
} else if (electionTimeoutMillisElement.isNumber()) {
_electionTimeoutPeriod = Milliseconds(electionTimeoutMillisElement.numberInt());
} else {
return Status(ErrorCodes::TypeMismatch,
str::stream() << "Expected type of " << kSettingsFieldName << "."
<< kElectionTimeoutFieldName
<< " to be a number, but found a value of type "
<< typeName(electionTimeoutMillisElement.type()));
}
//
// Parse heartbeatTimeoutSecs
//
BSONElement hbTimeoutSecsElement = settings[kHeartbeatTimeoutFieldName];
if (hbTimeoutSecsElement.eoo()) {
_heartbeatTimeoutPeriod = Seconds(kDefaultHeartbeatTimeoutPeriod);
} else if (hbTimeoutSecsElement.isNumber()) {
_heartbeatTimeoutPeriod = Seconds(hbTimeoutSecsElement.numberInt());
} else {
return Status(ErrorCodes::TypeMismatch,
str::stream() << "Expected type of " << kSettingsFieldName << "."
<< kHeartbeatTimeoutFieldName
<< " to be a number, but found a value of type "
<< typeName(hbTimeoutSecsElement.type()));
}
//
// Parse chainingAllowed
//
Status status = bsonExtractBooleanFieldWithDefault(
settings, kChainingAllowedFieldName, true, &_chainingAllowed);
if (!status.isOK())
return status;
//
// Parse getLastErrorDefaults
//
BSONElement gleDefaultsElement;
status = bsonExtractTypedField(
settings, kGetLastErrorDefaultsFieldName, Object, &gleDefaultsElement);
if (status.isOK()) {
status = _defaultWriteConcern.parse(gleDefaultsElement.Obj());
if (!status.isOK())
return status;
} else if (status == ErrorCodes::NoSuchKey) {
// Default write concern is w: 1.
_defaultWriteConcern.reset();
_defaultWriteConcern.wNumNodes = 1;
} else {
return status;
}
//
// Parse getLastErrorModes
//
BSONElement gleModesElement;
status = bsonExtractTypedField(settings, kGetLastErrorModesFieldName, Object, &gleModesElement);
BSONObj gleModes;
if (status.isOK()) {
gleModes = gleModesElement.Obj();
} else if (status != ErrorCodes::NoSuchKey) {
return status;
}
for (BSONObj::iterator gleModeIter(gleModes); gleModeIter.more();) {
const BSONElement modeElement = gleModeIter.next();
if (_customWriteConcernModes.find(modeElement.fieldNameStringData()) !=
_customWriteConcernModes.end()) {
return Status(ErrorCodes::DuplicateKey,
str::stream() << kSettingsFieldName << '.' << kGetLastErrorModesFieldName
<< " contains multiple fields named "
<< modeElement.fieldName());
}
if (modeElement.type() != Object) {
return Status(ErrorCodes::TypeMismatch,
str::stream() << "Expected " << kSettingsFieldName << '.'
<< kGetLastErrorModesFieldName << '.'
<< modeElement.fieldName() << " to be an Object, not "
<< typeName(modeElement.type()));
}
//.........这里部分代码省略.........
示例9: initialize
Status ReplSetHeartbeatResponse::initialize(const BSONObj& doc) {
// Old versions set this even though they returned not "ok"
_mismatch = doc[kMismatchFieldName].trueValue();
if (_mismatch)
return Status(ErrorCodes::InconsistentReplicaSetNames, "replica set name doesn't match.");
// Old versions sometimes set the replica set name ("set") but ok:0
const BSONElement replSetNameElement = doc[kReplSetFieldName];
if (replSetNameElement.eoo()) {
_setName.clear();
} else if (replSetNameElement.type() != String) {
return Status(ErrorCodes::TypeMismatch,
str::stream() << "Expected \"" << kReplSetFieldName
<< "\" field in response to replSetHeartbeat to have "
"type String, but found "
<< typeName(replSetNameElement.type()));
} else {
_setName = replSetNameElement.String();
}
if (_setName.empty() && !doc[kOkFieldName].trueValue()) {
std::string errMsg = doc[kErrMsgFieldName].str();
BSONElement errCodeElem = doc[kErrorCodeFieldName];
if (errCodeElem.ok()) {
if (!errCodeElem.isNumber())
return Status(ErrorCodes::BadValue, "Error code is not a number!");
int errorCode = errCodeElem.numberInt();
return Status(ErrorCodes::Error(errorCode), errMsg);
}
return Status(ErrorCodes::UnknownError, errMsg);
}
const BSONElement hasDataElement = doc[kHasDataFieldName];
_hasDataSet = !hasDataElement.eoo();
_hasData = hasDataElement.trueValue();
const BSONElement electionTimeElement = doc[kElectionTimeFieldName];
if (electionTimeElement.eoo()) {
_electionTimeSet = false;
} else if (electionTimeElement.type() == Timestamp) {
_electionTimeSet = true;
_electionTime = electionTimeElement._opTime();
} else if (electionTimeElement.type() == Date) {
_electionTimeSet = true;
_electionTime = OpTime(electionTimeElement.date());
} else {
return Status(ErrorCodes::TypeMismatch,
str::stream() << "Expected \"" << kElectionTimeFieldName
<< "\" field in response to replSetHeartbeat "
"command to have type Date or Timestamp, but found type "
<< typeName(electionTimeElement.type()));
}
const BSONElement timeElement = doc[kTimeFieldName];
if (timeElement.eoo()) {
_timeSet = false;
} else if (timeElement.isNumber()) {
_timeSet = true;
_time = Seconds(timeElement.numberLong());
} else {
return Status(ErrorCodes::TypeMismatch,
str::stream() << "Expected \"" << kTimeFieldName
<< "\" field in response to replSetHeartbeat "
"command to have a numeric type, but found type "
<< typeName(timeElement.type()));
}
const BSONElement opTimeElement = doc[kOpTimeFieldName];
if (opTimeElement.eoo()) {
_opTimeSet = false;
} else if (opTimeElement.type() == Timestamp) {
_opTimeSet = true;
_opTime = opTimeElement._opTime();
} else if (opTimeElement.type() == Date) {
_opTimeSet = true;
_opTime = OpTime(opTimeElement.date());
} else {
return Status(ErrorCodes::TypeMismatch,
str::stream() << "Expected \"" << kOpTimeFieldName
<< "\" field in response to replSetHeartbeat "
"command to have type Date or Timestamp, but found type "
<< typeName(opTimeElement.type()));
}
const BSONElement electableElement = doc[kIsElectableFieldName];
if (electableElement.eoo()) {
_electableSet = false;
} else {
_electableSet = true;
_electable = electableElement.trueValue();
}
_isReplSet = doc[kIsReplSetFieldName].trueValue();
const BSONElement memberStateElement = doc[kMemberStateFieldName];
if (memberStateElement.eoo()) {
_stateSet = false;
} else if (memberStateElement.type() != NumberInt && memberStateElement.type() != NumberLong) {
//.........这里部分代码省略.........
示例10: isValid
// static
Status CanonicalQuery::isValid(MatchExpression* root, const QueryRequest& parsed) {
// Analysis below should be done after squashing the tree to make it clearer.
// There can only be one TEXT. If there is a TEXT, it cannot appear inside a NOR.
//
// Note that the query grammar (as enforced by the MatchExpression parser) forbids TEXT
// inside of value-expression clauses like NOT, so we don't check those here.
size_t numText = countNodes(root, MatchExpression::TEXT);
if (numText > 1) {
return Status(ErrorCodes::BadValue, "Too many text expressions");
} else if (1 == numText) {
if (hasNodeInSubtree(root, MatchExpression::TEXT, MatchExpression::NOR)) {
return Status(ErrorCodes::BadValue, "text expression not allowed in nor");
}
}
// There can only be one NEAR. If there is a NEAR, it must be either the root or the root
// must be an AND and its child must be a NEAR.
size_t numGeoNear = countNodes(root, MatchExpression::GEO_NEAR);
if (numGeoNear > 1) {
return Status(ErrorCodes::BadValue, "Too many geoNear expressions");
} else if (1 == numGeoNear) {
bool topLevel = false;
if (MatchExpression::GEO_NEAR == root->matchType()) {
topLevel = true;
} else if (MatchExpression::AND == root->matchType()) {
for (size_t i = 0; i < root->numChildren(); ++i) {
if (MatchExpression::GEO_NEAR == root->getChild(i)->matchType()) {
topLevel = true;
break;
}
}
}
if (!topLevel) {
return Status(ErrorCodes::BadValue, "geoNear must be top-level expr");
}
}
// NEAR cannot have a $natural sort or $natural hint.
const BSONObj& sortObj = parsed.getSort();
BSONElement sortNaturalElt = sortObj["$natural"];
const BSONObj& hintObj = parsed.getHint();
BSONElement hintNaturalElt = hintObj["$natural"];
if (numGeoNear > 0) {
if (sortNaturalElt) {
return Status(ErrorCodes::BadValue,
"geoNear expression not allowed with $natural sort order");
}
if (hintNaturalElt) {
return Status(ErrorCodes::BadValue,
"geoNear expression not allowed with $natural hint");
}
}
// TEXT and NEAR cannot both be in the query.
if (numText > 0 && numGeoNear > 0) {
return Status(ErrorCodes::BadValue, "text and geoNear not allowed in same query");
}
// TEXT and {$natural: ...} sort order cannot both be in the query.
if (numText > 0 && sortNaturalElt) {
return Status(ErrorCodes::BadValue, "text expression not allowed with $natural sort order");
}
// TEXT and hint cannot both be in the query.
if (numText > 0 && !hintObj.isEmpty()) {
return Status(ErrorCodes::BadValue, "text and hint not allowed in same query");
}
// TEXT and tailable are incompatible.
if (numText > 0 && parsed.isTailable()) {
return Status(ErrorCodes::BadValue, "text and tailable cursor not allowed in same query");
}
// $natural sort order must agree with hint.
if (sortNaturalElt) {
if (!hintObj.isEmpty() && !hintNaturalElt) {
return Status(ErrorCodes::BadValue, "index hint not allowed with $natural sort order");
}
if (hintNaturalElt) {
if (hintNaturalElt.numberInt() != sortNaturalElt.numberInt()) {
return Status(ErrorCodes::BadValue,
"$natural hint must be in the same direction as $natural sort order");
}
}
}
return Status::OK();
}
示例11: fixSpec
BSONObj FTSSpec::fixSpec( const BSONObj& spec ) {
map<string,int> m;
BSONObj keyPattern;
{
BSONObjBuilder b;
bool addedFtsStuff = false;
BSONObjIterator i( spec["key"].Obj() );
while ( i.more() ) {
BSONElement e = i.next();
if ( str::equals( e.fieldName(), "_fts" ) ||
str::equals( e.fieldName(), "_ftsx" ) ) {
continue;
}
else if ( e.type() == String &&
( str::equals( "fts", e.valuestr() ) ||
str::equals( "text", e.valuestr() ) ) ) {
if ( !addedFtsStuff ) {
_addFTSStuff( &b );
addedFtsStuff = true;
}
m[e.fieldName()] = 1;
}
else {
b.append( e );
}
}
if ( !addedFtsStuff )
_addFTSStuff( &b );
keyPattern = b.obj();
}
if ( spec["weights"].isABSONObj() ) {
BSONObjIterator i( spec["weights"].Obj() );
while ( i.more() ) {
BSONElement e = i.next();
m[e.fieldName()] = e.numberInt();
}
}
else if ( spec["weights"].str() == WILDCARD ) {
m[WILDCARD] = 1;
}
BSONObj weights;
{
BSONObjBuilder b;
for ( map<string,int>::iterator i = m.begin(); i != m.end(); ++i )
b.append( i->first, i->second );
weights = b.obj();
}
string default_language(spec.getStringField("default_language"));
if ( default_language.empty() )
default_language = "english";
string language_override(spec.getStringField("language_override"));
if ( language_override.empty() )
language_override = "language";
int version = 0;
BSONObjBuilder b;
BSONObjIterator i( spec );
while ( i.more() ) {
BSONElement e = i.next();
if ( str::equals( e.fieldName(), "key" ) ) {
b.append( "key", keyPattern );
}
else if ( str::equals( e.fieldName(), "weights" ) ) {
b.append( "weights", weights );
weights = BSONObj();
}
else if ( str::equals( e.fieldName(), "default_language" ) ) {
b.append( "default_language", default_language);
default_language = "";
}
else if ( str::equals( e.fieldName(), "language_override" ) ) {
b.append( "language_override", language_override);
language_override = "";
}
else if ( str::equals( e.fieldName(), "v" ) ) {
version = e.numberInt();
}
else {
b.append( e );
}
}
if ( !weights.isEmpty() )
b.append( "weights", weights );
if ( !default_language.empty() )
b.append( "default_language", default_language);
if ( !language_override.empty() )
b.append( "language_override", language_override);
//.........这里部分代码省略.........
示例12: parse
///PD_TRACE_DECLARE_FUNCTION ( SDB__MTHSUBSTRPARSER_PARSE, "_mthSubStrParser::parse" )
INT32 _mthSubStrParser::parse( const bson::BSONElement &e,
_mthSAction &action ) const
{
INT32 rc = SDB_OK ;
PD_TRACE_ENTRY( SDB__MTHSUBSTRPARSER_PARSE ) ;
INT32 begin = 0 ;
INT32 limit = -1 ;
#if defined (_DEBUG)
if ( 0 != _name.compare( e.fieldName() ) )
{
PD_LOG( PDERROR, "field name[%s] is not valid",
e.fieldName() ) ;
rc = SDB_INVALIDARG ;
goto error ;
}
#endif
if ( e.isNumber() && 0 <= e.numberInt())
{
limit = e.numberInt() ;
}
else if ( e.isNumber() )
{
begin = e.numberInt() ;
}
else if ( Array == e.type() )
{
BSONObjIterator i( e.embeddedObject() ) ;
BSONElement ele ;
if ( !i.more() )
{
goto invalid_arg ;
}
ele = i.next() ;
if ( !ele.isNumber() )
{
goto invalid_arg ;
}
begin = ele.numberInt() ;
if ( !i.more() )
{
goto invalid_arg ;
}
ele = i.next() ;
if ( !ele.isNumber() )
{
goto invalid_arg ;
}
limit = ele.numberInt() ;
}
else
{
PD_LOG( PDERROR, "invalid element" ) ;
rc = SDB_INVALIDARG ;
goto error ;
}
action.setAttribute( MTH_S_ATTR_PROJECTION ) ;
action.setFunc( &mthSubStrBuild,
&mthSubStrGet ) ;
action.setName( _name.c_str() ) ;
action.setArg( BSON( "arg1" << begin << "arg2" << limit ) ) ;
done:
PD_TRACE_EXITRC( SDB__MTHSUBSTRPARSER_PARSE, rc ) ;
return rc ;
error:
goto done ;
invalid_arg:
PD_LOG( PDERROR, "invalid substr argument:%s",
e.toString( TRUE, TRUE ).c_str() ) ;
rc = SDB_INVALIDARG ;
goto error ;
}
示例13: _addANode
INT32 _omAgentNodeMgr::_addANode( const CHAR *arg1, const CHAR *arg2,
BOOLEAN needLock, BOOLEAN isModify,
string *omsvc )
{
INT32 rc = SDB_OK ;
const CHAR *pSvcName = NULL ;
const CHAR *pDBPath = NULL ;
string otherCfg ;
CHAR dbPath[ OSS_MAX_PATHSIZE + 1 ] = { 0 } ;
CHAR cfgPath[ OSS_MAX_PATHSIZE + 1 ] = { 0 } ;
CHAR cfgFile[ OSS_MAX_PATHSIZE + 1 ] = { 0 } ;
BOOLEAN createDBPath = FALSE ;
BOOLEAN createCfgPath = FALSE ;
BOOLEAN createCfgFile = FALSE ;
BOOLEAN hasLock = FALSE ;
try
{
stringstream ss ;
BSONObj objArg1( arg1 ) ;
BSONObjIterator it ( objArg1 ) ;
while ( it.more() )
{
BSONElement e = it.next() ;
if ( 0 == ossStrcmp( e.fieldName(), PMD_OPTION_SVCNAME ) )
{
if ( e.type() != String )
{
PD_LOG( PDERROR, "Param[%s] type[%d] is not string",
PMD_OPTION_SVCNAME, e.type() ) ;
rc = SDB_INVALIDARG ;
goto error ;
}
pSvcName = e.valuestrsafe() ;
}
else if ( 0 == ossStrcmp( e.fieldName(), PMD_OPTION_DBPATH ) )
{
if ( e.type() != String )
{
PD_LOG( PDERROR, "Param[%s] type[%d] is not string",
PMD_OPTION_DBPATH, e.type() ) ;
rc = SDB_INVALIDARG ;
goto error ;
}
pDBPath = e.valuestrsafe() ;
}
else
{
ss << e.fieldName() << "=" ;
switch( e.type() )
{
case NumberDouble :
ss << e.numberDouble () ;
break ;
case NumberInt :
ss << e.numberLong () ;
break ;
case NumberLong :
ss << e.numberInt () ;
break ;
case String :
ss << e.valuestrsafe () ;
break ;
case Bool :
ss << ( e.boolean() ? "TRUE" : "FALSE" ) ;
break ;
default :
PD_LOG ( PDERROR, "Unexpected type[%d] for %s",
e.type(), e.toString().c_str() ) ;
rc = SDB_INVALIDARG ;
goto error ;
}
ss << endl ;
}
}
otherCfg = ss.str() ;
}
catch( std::exception &e )
{
PD_LOG( PDERROR, "Occur exception: %s", e.what() ) ;
rc = SDB_INVALIDARG ;
goto error ;
}
if ( !pSvcName || !pDBPath )
{
PD_LOG( PDERROR, "Param [%s] or [%s] is not config",
PMD_OPTION_SVCNAME, PMD_OPTION_DBPATH ) ;
rc = SDB_INVALIDARG ;
goto error ;
}
if ( !ossGetRealPath( pDBPath, dbPath, OSS_MAX_PATHSIZE ) )
{
PD_LOG( PDERROR, "Invalid db path: %s", pDBPath ) ;
rc = SDB_INVALIDARG ;
goto error ;
}
//.........这里部分代码省略.........
示例14: specIt
void S2NearStage::init() {
_initted = true;
// The field we're near-ing from is the n-th field. Figure out what that 'n' is. We
// put the cover for the search annulus in this spot in the bounds.
_nearFieldIndex = 0;
BSONObjIterator specIt(_params.indexKeyPattern);
while (specIt.more()) {
if (specIt.next().fieldName() == _params.nearQuery.field) {
break;
}
++_nearFieldIndex;
}
verify(_nearFieldIndex < _params.indexKeyPattern.nFields());
// FLAT implies the distances are in radians. Convert to meters.
if (FLAT == _params.nearQuery.centroid.crs) {
_params.nearQuery.minDistance *= kRadiusOfEarthInMeters;
_params.nearQuery.maxDistance *= kRadiusOfEarthInMeters;
}
// Make sure distances are sane. Possibly redundant given the checking during parsing.
_minDistance = max(0.0, _params.nearQuery.minDistance);
_maxDistance = min(M_PI * kRadiusOfEarthInMeters, _params.nearQuery.maxDistance);
_minDistance = min(_minDistance, _maxDistance);
// We grow _outerRadius in nextAnnulus() below.
_innerRadius = _outerRadius = _minDistance;
_outerRadiusInclusive = false;
// Grab the IndexDescriptor.
Database* db = cc().database();
if (!db) {
_failed = true;
return;
}
Collection* collection = db->getCollection(_params.ns);
if (!collection) {
_failed = true;
return;
}
_descriptor = collection->getIndexCatalog()->findIndexByKeyPattern(_params.indexKeyPattern);
if (NULL == _descriptor) {
_failed = true;
return;
}
// The user can override this so we honor it. We could ignore it though -- it's just used
// to set _radiusIncrement, not to do any covering.
int finestIndexedLevel;
BSONElement fl = _descriptor->infoObj()["finestIndexedLevel"];
if (fl.isNumber()) {
finestIndexedLevel = fl.numberInt();
}
else {
finestIndexedLevel = S2::kAvgEdge.GetClosestLevel(500.0 / kRadiusOfEarthInMeters);
}
// Start with a conservative _radiusIncrement. When we're done searching a shell we
// increment the two radii by this.
_radiusIncrement = 5 * S2::kAvgEdge.GetValue(finestIndexedLevel) * kRadiusOfEarthInMeters;
}
示例15: RocksCounterManager
RocksEngine::RocksEngine(const std::string& path, bool durable)
: _path(path), _durable(durable), _maxPrefix(0) {
{ // create block cache
uint64_t cacheSizeGB = rocksGlobalOptions.cacheSizeGB;
if (cacheSizeGB == 0) {
ProcessInfo pi;
unsigned long long memSizeMB = pi.getMemSizeMB();
if (memSizeMB > 0) {
double cacheMB = memSizeMB / 2;
cacheSizeGB = static_cast<uint64_t>(cacheMB / 1024);
}
if (cacheSizeGB < 1) {
cacheSizeGB = 1;
}
}
_block_cache = rocksdb::NewLRUCache(cacheSizeGB * 1024 * 1024 * 1024LL, 6);
}
_maxWriteMBPerSec = rocksGlobalOptions.maxWriteMBPerSec;
_rateLimiter.reset(
rocksdb::NewGenericRateLimiter(static_cast<int64_t>(_maxWriteMBPerSec) * 1024 * 1024));
// open DB
rocksdb::DB* db;
auto s = rocksdb::DB::Open(_options(), path, &db);
invariantRocksOK(s);
_db.reset(db);
_counterManager.reset(
new RocksCounterManager(_db.get(), rocksGlobalOptions.crashSafeCounters));
_compactionScheduler.reset(new RocksCompactionScheduler(_db.get()));
// open iterator
boost::scoped_ptr<rocksdb::Iterator> iter(_db->NewIterator(rocksdb::ReadOptions()));
// find maxPrefix
iter->SeekToLast();
if (iter->Valid()) {
// otherwise the DB is empty, so we just keep it at 0
bool ok = extractPrefix(iter->key(), &_maxPrefix);
// this is DB corruption here
invariant(ok);
}
// load ident to prefix map. also update _maxPrefix if there's any prefix bigger than
// current _maxPrefix
{
boost::lock_guard<boost::mutex> lk(_identPrefixMapMutex);
for (iter->Seek(kMetadataPrefix);
iter->Valid() && iter->key().starts_with(kMetadataPrefix); iter->Next()) {
invariantRocksOK(iter->status());
rocksdb::Slice ident(iter->key());
ident.remove_prefix(kMetadataPrefix.size());
// this could throw DBException, which then means DB corruption. We just let it fly
// to the caller
BSONObj identConfig(iter->value().data());
BSONElement element = identConfig.getField("prefix");
if (element.eoo() || !element.isNumber()) {
log() << "Mongo metadata in RocksDB database is corrupted.";
invariant(false);
}
uint32_t identPrefix = static_cast<uint32_t>(element.numberInt());
_identPrefixMap[StringData(ident.data(), ident.size())] = identPrefix;
_maxPrefix = std::max(_maxPrefix, identPrefix);
}
}
// just to be extra sure. we need this if last collection is oplog -- in that case we
// reserve prefix+1 for oplog key tracker
++_maxPrefix;
// load dropped prefixes
{
rocksdb::WriteBatch wb;
// we will use this iter to check if prefixes are still alive
boost::scoped_ptr<rocksdb::Iterator> prefixIter(
_db->NewIterator(rocksdb::ReadOptions()));
for (iter->Seek(kDroppedPrefix);
iter->Valid() && iter->key().starts_with(kDroppedPrefix); iter->Next()) {
invariantRocksOK(iter->status());
rocksdb::Slice prefix(iter->key());
prefix.remove_prefix(kDroppedPrefix.size());
prefixIter->Seek(prefix);
invariantRocksOK(iter->status());
if (prefixIter->Valid() && prefixIter->key().starts_with(prefix)) {
// prefix is still alive, let's instruct the compaction filter to clear it up
uint32_t int_prefix;
bool ok = extractPrefix(prefix, &int_prefix);
invariant(ok);
{
boost::lock_guard<boost::mutex> lk(_droppedPrefixesMutex);
_droppedPrefixes.insert(int_prefix);
}
} else {
// prefix is no longer alive. let's remove the prefix from our dropped prefixes
// list
wb.Delete(iter->key());
}
}
//.........这里部分代码省略.........