本文整理汇总了C++中BSONArrayBuilder::arr方法的典型用法代码示例。如果您正苦于以下问题:C++ BSONArrayBuilder::arr方法的具体用法?C++ BSONArrayBuilder::arr怎么用?C++ BSONArrayBuilder::arr使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BSONArrayBuilder
的用法示例。
在下文中一共展示了BSONArrayBuilder::arr方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: toBSONArray
BSONArray MongoVersionRange::toBSONArray(const vector<MongoVersionRange>& ranges) {
BSONArrayBuilder barr;
for (vector<MongoVersionRange>::const_iterator it = ranges.begin(); it != ranges.end();
++it)
{
const MongoVersionRange& range = *it;
range.toBSONElement(&barr);
}
return barr.arr();
}
示例2: writeExplainShard
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());
}
示例3: handleCursorCommand
static void handleCursorCommand(CursorId id, BSONObj& cmdObj, BSONObjBuilder& result) {
BSONElement batchSizeElem = cmdObj.getFieldDotted("cursor.batchSize");
const long long batchSize = batchSizeElem.isNumber()
? batchSizeElem.numberLong()
: 101; // same as query
// Using limited cursor API that ignores many edge cases. Should be sufficient for commands.
ClientCursor::Pin pin(id);
ClientCursor* cursor = pin.c();
massert(16958, "Cursor shouldn't have been deleted",
cursor);
// Make sure this cursor won't disappear on us
fassert(16959, !cursor->c()->shouldDestroyOnNSDeletion());
fassert(16960, !cursor->c()->requiresLock());
try {
// can't use result BSONObjBuilder directly since it won't handle exceptions correctly.
BSONArrayBuilder resultsArray;
const int byteLimit = MaxBytesToReturnToClientAtOnce;
for (int objs = 0;
objs < batchSize && cursor->ok() && resultsArray.len() <= byteLimit;
objs++) {
// TODO may need special logic if cursor->current() would cause results to be > 16MB
resultsArray.append(cursor->current());
cursor->advance();
}
// The initial ok() on a cursor may be very expensive so we don't do it when batchSize
// is 0 since that indicates a desire for a fast return.
if (batchSize != 0 && !cursor->ok()) {
// There is no more data. Kill the cursor.
pin.release();
ClientCursor::erase(id);
id = 0;
}
BSONObjBuilder cursorObj(result.subobjStart("cursor"));
cursorObj.append("id", id);
cursorObj.append("ns", cursor->ns());
cursorObj.append("firstBatch", resultsArray.arr());
cursorObj.done();
}
catch (...) {
// Clean up cursor on way out of scope.
pin.release();
ClientCursor::erase(id);
throw;
}
}
示例4: newLockDetails
StatusWith<LocksType> DistLockCatalogImpl::overtakeLock(OperationContext* opCtx,
StringData lockID,
const OID& lockSessionID,
const OID& currentHolderTS,
StringData who,
StringData processId,
Date_t time,
StringData why) {
BSONArrayBuilder orQueryBuilder;
orQueryBuilder.append(
BSON(LocksType::name() << lockID << LocksType::state(LocksType::UNLOCKED)));
orQueryBuilder.append(BSON(LocksType::name() << lockID << LocksType::lockID(currentHolderTS)));
BSONObj newLockDetails(BSON(
LocksType::lockID(lockSessionID) << LocksType::state(LocksType::LOCKED) << LocksType::who()
<< who
<< LocksType::process()
<< processId
<< LocksType::when(time)
<< LocksType::why()
<< why));
auto request = FindAndModifyRequest::makeUpdate(
_locksNS, BSON("$or" << orQueryBuilder.arr()), BSON("$set" << newLockDetails));
request.setShouldReturnNew(true);
request.setWriteConcern(kMajorityWriteConcern);
auto const shardRegistry = Grid::get(opCtx)->shardRegistry();
auto resultStatus = shardRegistry->getConfigShard()->runCommandWithFixedRetryAttempts(
opCtx,
ReadPreferenceSetting{ReadPreference::PrimaryOnly},
_locksNS.db().toString(),
request.toBSON(),
Shard::kDefaultConfigCommandTimeout,
Shard::RetryPolicy::kNotIdempotent);
auto findAndModifyStatus = extractFindAndModifyNewObj(std::move(resultStatus));
if (!findAndModifyStatus.isOK()) {
return findAndModifyStatus.getStatus();
}
BSONObj doc = findAndModifyStatus.getValue();
auto locksTypeResult = LocksType::fromBSON(doc);
if (!locksTypeResult.isOK()) {
return {ErrorCodes::FailedToParse,
str::stream() << "failed to parse: " << doc << " : "
<< locksTypeResult.getStatus().toString()};
}
return locksTypeResult.getValue();
}
示例5: valueBson
/* ****************************************************************************
*
* ContextAttribute::valueBson -
*
* Used to render attribute value to BSON, appended into the bsonAttr builder
*/
void ContextAttribute::valueBson(BSONObjBuilder& bsonAttr, const std::string& attrType, bool autocast, bool strings2numbers) const
{
if (compoundValueP == NULL)
{
bsonAppendAttrValue(bsonAttr, attrType, autocast);
}
else
{
if (compoundValueP->valueType == ValueTypeVector)
{
BSONArrayBuilder b;
compoundValueBson(compoundValueP->childV, b, strings2numbers);
bsonAttr.append(ENT_ATTRS_VALUE, b.arr());
}
else if (compoundValueP->valueType == ValueTypeObject)
{
BSONObjBuilder b;
compoundValueBson(compoundValueP->childV, b, strings2numbers);
bsonAttr.append(ENT_ATTRS_VALUE, b.obj());
}
else if (compoundValueP->valueType == ValueTypeString)
{
// FIXME P4: this is somehow redundant. See https://github.com/telefonicaid/fiware-orion/issues/271
bsonAttr.append(ENT_ATTRS_VALUE, compoundValueP->stringValue);
}
else if (compoundValueP->valueType == ValueTypeNumber)
{
// FIXME P4: this is somehow redundant. See https://github.com/telefonicaid/fiware-orion/issues/271
bsonAttr.append(ENT_ATTRS_VALUE, compoundValueP->numberValue);
}
else if (compoundValueP->valueType == ValueTypeBoolean)
{
// FIXME P4: this is somehow redundant. See https://github.com/telefonicaid/fiware-orion/issues/271
bsonAttr.append(ENT_ATTRS_VALUE, compoundValueP->boolValue);
}
else if (compoundValueP->valueType == ValueTypeNull)
{
// FIXME P4: this is somehow redundant. See https://github.com/telefonicaid/fiware-orion/issues/271
bsonAttr.appendNull(ENT_ATTRS_VALUE);
}
else if (compoundValueP->valueType == ValueTypeNotGiven)
{
LM_E(("Runtime Error (value not given in compound value)"));
}
else
{
LM_E(("Runtime Error (Unknown type in compound value)"));
}
}
}
示例6: run
void run() {
ShardKeyPattern shardKeyPattern(shardKey());
ChunkManager chunkManager("", shardKeyPattern, false);
chunkManager.setSingleChunkForShards( splitPointsVector() );
set<Shard> shards;
chunkManager.getShardsForQuery( shards, query() );
BSONArrayBuilder b;
for( set<Shard>::const_iterator i = shards.begin(); i != shards.end(); ++i ) {
b << i->getName();
}
ASSERT_EQUALS( expectedShardNames(), b.arr() );
}
示例7: run
bool Pipeline::run(BSONObjBuilder &result, string &errmsg,
const intrusive_ptr<DocumentSource> &pInputSource) {
/* chain together the sources we found */
DocumentSource *pSource = pInputSource.get();
for(SourceVector::iterator iter(sourceVector.begin()),
listEnd(sourceVector.end()); iter != listEnd; ++iter) {
intrusive_ptr<DocumentSource> pTemp(*iter);
pTemp->setSource(pSource);
pSource = pTemp.get();
}
/* pSource is left pointing at the last source in the chain */
/*
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, pInputSource);
else {
writeExplainMongos(result, pInputSource);
}
}
else {
// the array in which the aggregation results reside
// cant use subArrayStart() due to error handling
BSONArrayBuilder resultArray;
for(bool hasDoc = !pSource->eof(); hasDoc; hasDoc = pSource->advance()) {
intrusive_ptr<Document> pDocument(pSource->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;
}
示例8: ls
BSONObj ls(const BSONObj& args, void* data) {
BSONArrayBuilder ret;
BSONObj o = listFiles(args, data);
if (!o.isEmpty()) {
for (BSONObj::iterator i = o.firstElement().Obj().begin(); i.more();) {
BSONObj f = i.next().Obj();
string name = f["name"].String();
if (f["isDirectory"].trueValue()) {
name += '/';
}
ret << name;
}
}
return BSON("" << ret.arr());
}
示例9: _buildNewDeletor
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() ;
}
示例10: run
bool run(OperationContext* txn,
const string& dbname,
BSONObj& cmdObj,
int,
string& errmsg,
BSONObjBuilder& result,
bool /*fromRepl*/) {
BSONElement first = cmdObj.firstElement();
uassert(
28528,
str::stream() << "Argument to listIndexes must be of type String, not "
<< typeName(first.type()),
first.type() == String);
const NamespaceString ns(parseNs(dbname, cmdObj));
uassert(
28529,
str::stream() << "Argument to listIndexes must be a collection name, "
<< "not the empty string",
!ns.coll().empty());
AutoGetCollectionForRead autoColl(txn, ns);
if (!autoColl.getDb()) {
return appendCommandStatus( result, Status( ErrorCodes::NamespaceNotFound,
"no database" ) );
}
const Collection* collection = autoColl.getCollection();
if (!collection) {
return appendCommandStatus( result, Status( ErrorCodes::NamespaceNotFound,
"no collection" ) );
}
const CollectionCatalogEntry* cce = collection->getCatalogEntry();
invariant(cce);
vector<string> indexNames;
cce->getAllIndexes( txn, &indexNames );
BSONArrayBuilder arr;
for ( size_t i = 0; i < indexNames.size(); i++ ) {
arr.append( cce->getIndexSpec( txn, indexNames[i] ) );
}
result.append( "indexes", arr.arr() );
return true;
}
示例11: run
virtual bool run(OperationContext* txn,
const string& dbname,
BSONObj& cmdObj,
int,
string& errmsg,
BSONObjBuilder& result) {
boost::optional<DisableDocumentValidation> maybeDisableValidation;
if (shouldBypassDocumentValidationforCommand(cmdObj))
maybeDisableValidation.emplace(txn);
string from = cmdObj.getStringField("clone");
if ( from.empty() )
return false;
CloneOptions opts;
opts.fromDB = dbname;
opts.slaveOk = cmdObj["slaveOk"].trueValue();
// See if there's any collections we should ignore
if( cmdObj["collsToIgnore"].type() == Array ){
BSONObjIterator it( cmdObj["collsToIgnore"].Obj() );
while( it.more() ){
BSONElement e = it.next();
if( e.type() == String ){
opts.collsToIgnore.insert( e.String() );
}
}
}
set<string> clonedColls;
ScopedTransaction transaction(txn, MODE_IX);
Lock::DBLock dbXLock(txn->lockState(), dbname, MODE_X);
Cloner cloner;
bool rval = cloner.go(txn, dbname, from, opts, &clonedColls, errmsg);
BSONArrayBuilder barr;
barr.append( clonedColls );
result.append( "clonedColls", barr.arr() );
return rval;
}
示例12: asBson
bo ReplSetConfig::asBson() const {
bob b;
b.append("_id", _id).append("version", version);
BSONArrayBuilder a;
for( unsigned i = 0; i < members.size(); i++ )
a.append( members[i].asBson() );
b.append("members", a.arr());
BSONObjBuilder settings;
bool empty = true;
if (!rules.empty()) {
bob modes;
for (map<string,TagRule*>::const_iterator it = rules.begin(); it != rules.end(); it++) {
bob clauses;
vector<TagClause*> r = (*it).second->clauses;
for (vector<TagClause*>::iterator it2 = r.begin(); it2 < r.end(); it2++) {
clauses << (*it2)->name << (*it2)->target;
}
modes << (*it).first << clauses.obj();
}
settings << "getLastErrorModes" << modes.obj();
empty = false;
}
if (!getLastErrorDefaults.isEmpty()) {
settings << "getLastErrorDefaults" << getLastErrorDefaults;
empty = false;
}
if (_heartbeatTimeout != DEFAULT_HB_TIMEOUT) {
settings << "heartbeatTimeoutSecs" << _heartbeatTimeout;
empty = false;
}
if (!_chainingAllowed) {
settings << "chainingAllowed" << _chainingAllowed;
empty = false;
}
if (!empty) {
b << "settings" << settings.obj();
}
return b.obj();
}
示例13: advertiseMechanismNamesForUser
void SASLServerMechanismRegistry::advertiseMechanismNamesForUser(OperationContext* opCtx,
const BSONObj& isMasterCmd,
BSONObjBuilder* builder) {
BSONElement saslSupportedMechs = isMasterCmd["saslSupportedMechs"];
if (saslSupportedMechs.type() == BSONType::String) {
const auto userName = uassertStatusOK(UserName::parse(saslSupportedMechs.String()));
AuthorizationManager* authManager = AuthorizationManager::get(opCtx->getServiceContext());
UserHandle user;
const auto swUser = authManager->acquireUser(opCtx, userName);
if (!swUser.isOK()) {
auto& status = swUser.getStatus();
if (status.code() == ErrorCodes::UserNotFound) {
log() << "Supported SASL mechanisms requested for unknown user '" << userName
<< "'";
return;
}
uassertStatusOK(status);
}
user = std::move(swUser.getValue());
BSONArrayBuilder mechanismsBuilder;
const auto& mechList = _getMapRef(userName.getDB());
for (const auto& factoryIt : mechList) {
SecurityPropertySet properties = factoryIt->properties();
if (!properties.hasAllProperties(SecurityPropertySet{SecurityProperty::kNoPlainText,
SecurityProperty::kMutualAuth}) &&
userName.getDB() != "$external") {
continue;
}
auto mechanismEnabled = _mechanismSupportedByConfig(factoryIt->mechanismName());
if (!mechanismEnabled && userName == internalSecurity.user->getName()) {
mechanismEnabled = factoryIt->isInternalAuthMech();
}
if (mechanismEnabled && factoryIt->canMakeMechanismForUser(user.get())) {
mechanismsBuilder << factoryIt->mechanismName();
}
}
builder->appendArray("saslSupportedMechs", mechanismsBuilder.arr());
}
}
示例14: newLockDetails
StatusWith<LocksType> DistLockCatalogImpl::overtakeLock(StringData lockID,
const OID& lockSessionID,
const OID& currentHolderTS,
StringData who,
StringData processId,
Date_t time,
StringData why) {
BSONArrayBuilder orQueryBuilder;
orQueryBuilder.append(
BSON(LocksType::name() << lockID << LocksType::state(LocksType::UNLOCKED)));
orQueryBuilder.append(BSON(LocksType::name() << lockID << LocksType::lockID(currentHolderTS)));
BSONObj newLockDetails(BSON(LocksType::lockID(lockSessionID)
<< LocksType::state(LocksType::LOCKED) << LocksType::who() << who
<< LocksType::process() << processId << LocksType::when(time)
<< LocksType::why() << why));
auto request = FindAndModifyRequest::makeUpdate(
_locksNS, BSON("$or" << orQueryBuilder.arr()), BSON("$set" << newLockDetails));
request.setShouldReturnNew(true);
request.setWriteConcern(_writeConcern);
auto resultStatus = _client->runCommandWithNotMasterRetries(
"config", _locksNS.db().toString(), request.toBSON());
if (!resultStatus.isOK()) {
return resultStatus.getStatus();
}
BSONObj responseObj(resultStatus.getValue());
auto findAndModifyStatus = extractFindAndModifyNewObj(responseObj);
if (!findAndModifyStatus.isOK()) {
return findAndModifyStatus.getStatus();
}
BSONObj doc = findAndModifyStatus.getValue();
auto locksTypeResult = LocksType::fromBSON(doc);
if (!locksTypeResult.isOK()) {
return {ErrorCodes::FailedToParse,
str::stream() << "failed to parse: " << doc << " : "
<< locksTypeResult.getStatus().toString()};
}
return locksTypeResult.getValue();
}
示例15: cursor
// SERVER-15899: test iteration using a path that generates no elements, but traverses a long
// array containing subdocuments with nested arrays.
TEST(Path, NonMatchingLongArrayOfSubdocumentsWithNestedArrays) {
ElementPath p;
ASSERT(p.init("a.b.x").isOK());
// Build the document {a: [{b: []}, {b: []}, {b: []}, ...]}.
BSONObj subdoc = BSON("b" << BSONArray());
BSONArrayBuilder builder;
for (int i = 0; i < 100 * 1000; ++i) {
builder.append(subdoc);
}
BSONObj doc = BSON("a" << builder.arr());
BSONElementIterator cursor(&p, doc);
// The path "a.b.x" matches no elements.
ASSERT(!cursor.more());
}