Esempio n. 1
0
 void S2AccessMethod::getOneLiteralKey(const BSONElement& elt, BSONObjSet* out) const {
     if (Array == elt.type()) {
         getLiteralKeysArray(elt.Obj(), out);
     } else {
         // One thing, not an array, index as-is.
         BSONObjBuilder b;
         b.appendAs(elt, "");
         out->insert(b.obj());
     }
 }
Esempio n. 2
0
    GridFSChunk GridFile::getChunk( int n ) const {
        _exists();
        BSONObjBuilder b;
        b.appendAs( _obj["_id"] , "files_id" );
        b.append( "n" , n );

        BSONObj o = _grid->_client.findOne( _grid->_chunksNS.c_str() , b.obj() );
        uassert( 10014 ,  "chunk is empty!" , ! o.isEmpty() );
        return GridFSChunk(o);
    }
Esempio n. 3
0
    Status ProjectionStage::transform(WorkingSetMember* member) {
        // The default no-fast-path case.
        if (ProjectionStageParams::NO_FAST_PATH == _projImpl) {
            return _exec->transform(member);
        }

        BSONObjBuilder bob;

        // Note that even if our fast path analysis is bug-free something that is
        // covered might be invalidated and just be an obj.  In this case we just go
        // through the SIMPLE_DOC path which is still correct if the covered data
        // is not available.
        //
        // SIMPLE_DOC implies that we expect an object so it's kind of redundant.
        if ((ProjectionStageParams::SIMPLE_DOC == _projImpl) || member->hasObj()) {
            // If we got here because of SIMPLE_DOC the planner shouldn't have messed up.
            invariant(member->hasObj());

            // Look at every field in the source document and see if we're including it.
            BSONObjIterator inputIt(member->obj);
            while (inputIt.more()) {
                BSONElement elt = inputIt.next();
                unordered_set<StringData, StringData::Hasher>::iterator fieldIt;
                fieldIt = _includedFields.find(elt.fieldNameStringData());
                if (_includedFields.end() != fieldIt) {
                    // If so, add it to the builder.
                    bob.append(elt);
                }
            }
        }
        else {
            invariant(ProjectionStageParams::COVERED_ONE_INDEX == _projImpl);
            // We're pulling data out of the key.
            invariant(1 == member->keyData.size());
            size_t keyIndex = 0;

            // Look at every key element...
            BSONObjIterator keyIterator(member->keyData[0].keyData);
            while (keyIterator.more()) {
                BSONElement elt = keyIterator.next();
                // If we're supposed to include it...
                if (_includeKey[keyIndex]) {
                    // Do so.
                    bob.appendAs(elt, _keyFieldNames[keyIndex]);
                }
                ++keyIndex;
            }
        }

        member->state = WorkingSetMember::OWNED_OBJ;
        member->keyData.clear();
        member->loc = DiskLoc();
        member->obj = bob.obj();
        return Status::OK();
    }
Esempio n. 4
0
    void Projection::append( BSONObjBuilder& b , const BSONElement& e, const MatchDetails* details,
                             const ArrayOpType arrayOpType ) const {

        FieldMap::const_iterator field = _fields.find( e.fieldName() );
        if (field == _fields.end()) {
            if (_include)
                b.append(e);
        }
        else {
            Projection& subfm = *field->second;
            if ( ( subfm._fields.empty() && !subfm._special ) ||
                 !(e.type()==Object || e.type()==Array) ) {
                // field map empty, or element is not an array/object
                if (subfm._include)
                    b.append(e);
            }
            else if (e.type() == Object) {
                BSONObjBuilder subb;
                BSONObjIterator it(e.embeddedObject());
                while (it.more()) {
                    subfm.append(subb, it.next(), details, arrayOpType);
                }
                b.append(e.fieldName(), subb.obj());
            }
            else { //Array
                BSONObjBuilder matchedBuilder;
                if ( details && ( arrayOpType == ARRAY_OP_POSITIONAL ||
                        arrayOpType == ARRAY_OP_POSITIONAL_KEYED )) {
                    // $ positional operator specified

                    LOG(4) << "projection: checking if element " << e << " matched spec: "
                           << getSpec() << " match details: " << *details << endl;
                    uassert( 16352, mongoutils::str::stream() << "positional operator ("
                                        << e.fieldName()
                                        << ".$) requires corresponding field in query specifier",
                                   details && details->hasElemMatchKey() );

                    uassert( 16353, "positional operator element mismatch",
                             ! e.embeddedObject()[details->elemMatchKey()].eoo() );

                    // append as the first element in the projected array
                    matchedBuilder.appendAs( e.embeddedObject()[details->elemMatchKey()], "0" );
                    // append the key as the second element in the projected array
                    if ( arrayOpType == ARRAY_OP_POSITIONAL_KEYED ) {
                        matchedBuilder.append( "1", details->elemMatchKey() );
                    }
                }
                else {
                    // append exact array; no subarray matcher specified
                    subfm.appendArray( matchedBuilder, e.embeddedObject() );
                }
                b.appendArray( e.fieldName(), matchedBuilder.obj() );
            }
        }
    }
Esempio n. 5
0
// If the element is something like:
//   a : { $gt : 3 }
// we append
//   a : 3
// else we just append the element.
//
    void appendElementHandlingGtLt(BSONObjBuilder& b, const BSONElement& e) {
        if ( e.type() == Object ) {
            BSONElement fe = e.embeddedObject().firstElement();
            const char *fn = fe.fieldName();
            if ( fn[0] == '$' && fn[1] && fn[2] == 't' ) {
                b.appendAs(fe, e.fieldName());
                return;
            }
        }
        b.append(e);
    }
Esempio n. 6
0
        // Build a new BSONObj with root in it.  If e is non-empty, append that to the key.  Insert
        // the BSONObj into keys.
        void addKey(const string& root, const BSONElement& e, BSONObjSet& keys) const {
            BSONObjBuilder buf;
            buf.append("", root);

            if (e.eoo())
                buf.appendNull("");
            else
                buf.appendAs(e, "");

            keys.insert(buf.obj());
        }
Esempio n. 7
0
        void _add( const BSONObj& obj, const string& root , const BSONElement& e , BSONObjSet& keys ) const {
            BSONObjBuilder buf;
            buf.append( "" , root );
            if ( e.eoo() )
                buf.appendNull( "" );
            else
                buf.appendAs( e , "" );

            BSONObj key = buf.obj();
            GEOQUADDEBUG( obj << "\n\t" << root << "\n\t" << key );
            keys.insert( key );
        }
StatusWith<BSONObj> ShardKeyPattern::extractShardKeyFromQuery(const BSONObj& basicQuery) const {
    if (!isValid())
        return StatusWith<BSONObj>(BSONObj());

    // Extract equalities from query
    CanonicalQuery* rawQuery;
    Status queryStatus =
        CanonicalQuery::canonicalize("", basicQuery, &rawQuery, WhereCallbackNoop());
    if (!queryStatus.isOK())
        return StatusWith<BSONObj>(queryStatus);
    scoped_ptr<CanonicalQuery> query(rawQuery);

    EqualityMatches equalities;
    // TODO: Build the path set initially?
    FieldRefSet keyPatternPathSet(_keyPatternPaths.vector());
    // We only care about extracting the full key pattern paths - if they don't exist (or are
    // conflicting), we don't contain the shard key.
    Status eqStatus =
        pathsupport::extractFullEqualityMatches(*query->root(), keyPatternPathSet, &equalities);
    // NOTE: Failure to extract equality matches just means we return no shard key - it's not
    // an error we propagate
    if (!eqStatus.isOK())
        return StatusWith<BSONObj>(BSONObj());

    // Extract key from equalities
    // NOTE: The method below is equivalent to constructing a BSONObj and running
    // extractShardKeyFromMatchable, but doesn't require creating the doc.

    BSONObjBuilder keyBuilder;
    // Iterate the parsed paths to avoid re-parsing
    for (OwnedPointerVector<FieldRef>::const_iterator it = _keyPatternPaths.begin();
         it != _keyPatternPaths.end();
         ++it) {
        const FieldRef& patternPath = **it;
        BSONElement equalEl = findEqualityElement(equalities, patternPath);

        if (!isShardKeyElement(equalEl, false))
            return StatusWith<BSONObj>(BSONObj());

        if (isHashedPattern()) {
            keyBuilder.append(
                patternPath.dottedField(),
                BSONElementHasher::hash64(equalEl, BSONElementHasher::DEFAULT_HASH_SEED));
        } else {
            // NOTE: The equal element may *not* have the same field name as the path -
            // nested $and, $eq, for example
            keyBuilder.appendAs(equalEl, patternPath.dottedField());
        }
    }

    dassert(isShardKey(keyBuilder.asTempObj()));
    return StatusWith<BSONObj>(keyBuilder.obj());
}
Esempio n. 9
0
BSONObj BatchedUpsertDetail::toBSON() const {
    BSONObjBuilder builder;

    if (_isIndexSet)
        builder.append(index(), _index);

    // We're using the BSONObj to store the _id value.
    if (_isUpsertedIDSet) {
        builder.appendAs(_upsertedID.firstElement(), upsertedID());
    }

    return builder.obj();
}
Esempio n. 10
0
    BSONObj Helpers::toKeyFormat( const BSONObj& o , BSONObj& key ) {
        BSONObjBuilder me;
        BSONObjBuilder k;

        BSONObjIterator i( o );
        while ( i.more() ) {
            BSONElement e = i.next();
            k.append( e.fieldName() , 1 );
            me.appendAs( e , "" );
        }
        key = k.obj();
        return me.obj();
    }
Esempio n. 11
0
 void nested2dotted(BSONObjBuilder& b, const BSONObj& obj, const string& base){
     BSONObjIterator it(obj);
     while (it.more()){
         BSONElement e = it.next();
         if (e.type() == Object){
             string newbase = base + e.fieldName() + ".";
             nested2dotted(b, e.embeddedObject(), newbase);
         }else{
             string newbase = base + e.fieldName();
             b.appendAs(e, newbase.c_str());
         }
     }
 }
Esempio n. 12
0
 /**
  sets element field names to empty string
  If a field in pattern is missing, it is omitted from the returned
  object.
  */
 BSONObj BSONObj::extractFieldsUnDotted(BSONObj pattern) const {
     BSONObjBuilder b;
     BSONObjIterator i(pattern);
     while ( i.more() ) {
         BSONElement e = i.next();
         if ( e.eoo() )
             break;
         BSONElement x = getField(e.fieldName());
         if ( !x.eoo() )
             b.appendAs(x, "");
     }
     return b.obj();
 }
Esempio n. 13
0
BSONObj FTSIndexFormat::getIndexKey(double weight,
                                    const string& term,
                                    const BSONObj& indexPrefix,
                                    TextIndexVersion textIndexVersion) {
    BSONObjBuilder b;

    BSONObjIterator i(indexPrefix);
    while (i.more()) {
        b.appendAs(i.next(), "");
    }

    _appendIndexKey(b, weight, term, textIndexVersion);
    return b.obj();
}
Esempio n. 14
0
StatusWith<BSONObj> SortKeyGenerator::getSortKeyFromIndexKey(const WorkingSetMember& member) const {
    invariant(member.getState() == WorkingSetMember::RID_AND_IDX);
    invariant(!_sortHasMeta);

    BSONObjBuilder sortKeyObj;
    for (BSONElement specElt : _rawSortSpec) {
        invariant(specElt.isNumber());
        BSONElement sortKeyElt;
        invariant(member.getFieldDotted(specElt.fieldName(), &sortKeyElt));
        sortKeyObj.appendAs(sortKeyElt, "");
    }

    return sortKeyObj.obj();
}
Esempio n. 15
0
    IndexScan* createIndexScan(BSONObj startKey,
                               BSONObj endKey,
                               bool startInclusive,
                               bool endInclusive,
                               int direction = 1) {
        IndexCatalog* catalog = _coll->getIndexCatalog();
        IndexDescriptor* descriptor = catalog->findIndexByKeyPattern(&_txn, BSON("x" << 1));
        invariant(descriptor);

        IndexScanParams params;
        params.descriptor = descriptor;
        params.direction = direction;

        OrderedIntervalList oil("x");
        BSONObjBuilder bob;
        bob.appendAs(startKey.firstElement(), "");
        bob.appendAs(endKey.firstElement(), "");
        oil.intervals.push_back(Interval(bob.obj(), startInclusive, endInclusive));
        params.bounds.fields.push_back(oil);

        MatchExpression* filter = NULL;
        return new IndexScan(&_txn, params, &_ws, filter);
    }
Esempio n. 16
0
    IndexScan* createIndexScan(BSONObj startKey,
                               BSONObj endKey,
                               bool startInclusive,
                               bool endInclusive,
                               int direction = 1) {
        IndexCatalog* catalog = _coll->getIndexCatalog();
        std::vector<IndexDescriptor*> indexes;
        catalog->findIndexesByKeyPattern(&_opCtx, BSON("x" << 1), false, &indexes);
        ASSERT_EQ(indexes.size(), 1U);

        IndexScanParams params(&_opCtx, *indexes[0]);
        params.direction = direction;

        OrderedIntervalList oil("x");
        BSONObjBuilder bob;
        bob.appendAs(startKey.firstElement(), "");
        bob.appendAs(endKey.firstElement(), "");
        oil.intervals.push_back(Interval(bob.obj(), startInclusive, endInclusive));
        params.bounds.fields.push_back(oil);

        MatchExpression* filter = NULL;
        return new IndexScan(&_opCtx, params, &_ws, filter);
    }
Esempio n. 17
0
    bool OplogReader::passthroughHandshake(const BSONObj& rid, const int nextOnChainId) {
        BSONObjBuilder cmd;
        cmd.appendAs(rid["_id"], "handshake");
        if (theReplSet) {
            const Member* chainedMember = theReplSet->findById(nextOnChainId);
            if (chainedMember != NULL) {
                cmd.append("config", chainedMember->config().asBson());
            }
        }
        cmd.append("member", nextOnChainId);

        BSONObj res;
        return conn()->runCommand("admin", cmd.obj(), res);
    }
Esempio n. 18
0
      // PD_TRACE_DECLARE_FUNCTION ( SDB__IXMKEYGEN__GENKEYSWITHNORMALELE, "_ixmKeyGenerator::_genKeyWithNormalEle" )
      INT32 _genKeyWithNormalEle( BSONElement *keyELes,
                                  UINT32 eleNum,
                                  BSONObjSet &keys ) const
      {
         PD_TRACE_ENTRY ( SDB__IXMKEYGEN__GENKEYSWITHNORMALELE );
         INT32 rc = SDB_OK ;
         BSONObjBuilder builder ;
         for ( UINT32 i = 0; i < eleNum; i++ )
         {
            BSONElement &e = keyELes[i] ;
            if ( e.eoo() )
            {
               builder.appendAs( gUndefinedElt, "" ) ;
            }
            else
            {
               builder.appendAs( e, "" ) ;
            }
         }

         keys.insert( builder.obj() ) ;
         PD_TRACE_EXITRC ( SDB__IXMKEYGEN__GENKEYSWITHNORMALELE, rc );
         return rc ;
      }
Esempio n. 19
0
LegacyReply::LegacyReply(const Message* message) {
    invariant(message->operation() == opReply);

    QueryResult::View qr = message->singleData().view2ptr();

    // should be checked by caller.
    invariant(qr.msgdata().getNetworkOp() == opReply);

    uassert(ErrorCodes::BadValue,
            str::stream() << "Got legacy command reply with a bad cursorId field,"
                          << " expected a value of 0 but got "
                          << qr.getCursorId(),
            qr.getCursorId() == 0);

    uassert(ErrorCodes::BadValue,
            str::stream() << "Got legacy command reply with a bad nReturned field,"
                          << " expected a value of 1 but got "
                          << qr.getNReturned(),
            qr.getNReturned() == 1);

    uassert(ErrorCodes::BadValue,
            str::stream() << "Got legacy command reply with a bad startingFrom field,"
                          << " expected a value of 0 but got "
                          << qr.getStartingFrom(),
            qr.getStartingFrom() == 0);

    auto status = Validator<BSONObj>::validateLoad(qr.data(), qr.dataLen());
    uassert(ErrorCodes::InvalidBSON,
            str::stream() << "Got legacy command reply with invalid BSON in the metadata field"
                          << causedBy(status),
            status.isOK());

    _commandReply = BSONObj(qr.data());
    _commandReply.shareOwnershipWith(message->sharedBuffer());

    if (_commandReply.firstElementFieldName() == "$err"_sd) {
        // Upconvert legacy errors.
        BSONObjBuilder bob;
        bob.appendAs(_commandReply.firstElement(), "errmsg");
        bob.append("ok", 0.0);
        if (auto code = _commandReply["code"]) {
            bob.append(code);
        }
        _commandReply = bob.obj();
    }

    return;
}
Esempio n. 20
0
    bool replHandshake(DBClientConnection *conn, const BSONObj& me) {
        string myname = getHostName();

        BSONObjBuilder cmd;
        cmd.appendAs( me["_id"] , "handshake" );
        if (theReplSet) {
            cmd.append("member", theReplSet->selfId());
            cmd.append("config", theReplSet->myConfig().asBson());
        }

        BSONObj res;
        bool ok = conn->runCommand( "admin" , cmd.obj() , res );
        // ignoring for now on purpose for older versions
        LOG( ok ? 1 : 0 ) << "replHandshake res not: " << ok << " res: " << res << endl;
        return true;
    }
Esempio n. 21
0
    /* makes a new BSONObj with the fields specified in pattern.
       fields returned in the order they appear in pattern.
       if any field missing or undefined in the original object, that field
       in the output will be null.

       n^2 implementation bad if pattern and object have lots
       of fields - normally pattern doesn't so should be fine.
    */
    BSONObj BSONObj::extractFieldsDotted(BSONObj pattern) const {
        BSONObjBuilder b;
        BSONObjIterator i(pattern);
        while (i.more()) {
            BSONElement e = i.next();
            const char *name = e.fieldName();

            BSONElement x = getFieldDotted( name );
            if ( x.eoo() || x.type() == Undefined ) {
                b.appendNull(name);
            } else {
                b.appendAs(x, name);
            }
        }
        return b.done();
    }
Esempio n. 22
0
 void S2AccessMethod::getLiteralKeysArray(const BSONObj& obj, BSONObjSet* out) const {
     BSONObjIterator objIt(obj);
     if (!objIt.more()) {
         // Empty arrays are indexed as undefined.
         BSONObjBuilder b;
         b.appendUndefined("");
         out->insert(b.obj());
     } else {
         // Non-empty arrays are exploded.
         while (objIt.more()) {
             BSONObjBuilder b;
             b.appendAs(objIt.next(), "");
             out->insert(b.obj());
         }
     }
 }
Esempio n. 23
0
    // static
    Status ProjectionExecutor::applyFindSyntax(const FindProjection* proj, WorkingSetMember* wsm) {
        BSONObjBuilder bob;
        if (proj->_includeID) {
            BSONElement elt;
            if (!wsm->getFieldDotted("_id", &elt)) {
                return Status(ErrorCodes::BadValue, "Couldn't get _id field in proj");
            }
            bob.append(elt);
        }

        if (proj->_includedFields.size() > 0) {
            // We only want stuff in _fields.
            const vector<string>& fields = proj->_includedFields;
            for (size_t i = 0; i < fields.size(); ++i) {
                BSONElement elt;
                // We can project a field that doesn't exist.  We just ignore it.
                // UNITTEST 11738048
                if (wsm->getFieldDotted(fields[i], &elt) && !elt.eoo()) {
                    // TODO: This fails utterly for dotted fields.  Fix.
                    bob.appendAs(elt, fields[i]);
                }
            }
        }
        else if (proj->_excludedFields.size() > 0) {
            // We want stuff NOT in _fields.  This can't be covered, so we expect an obj.
            if (!wsm->hasObj()) {
                return Status(ErrorCodes::BadValue,
                        "exclusion specified for projection but no obj to iter over");
            }
            const unordered_set<string>& fields = proj->_excludedFields;
            BSONObjIterator it(wsm->obj);
            while (it.more()) {
                BSONElement elt = it.next();
                if (!mongoutils::str::equals("_id", elt.fieldName())) {
                    if (fields.end() == fields.find(elt.fieldName())) {
                        bob.append(elt);
                    }
                }
            }
        }

        wsm->state = WorkingSetMember::OWNED_OBJ;
        wsm->obj = bob.obj();
        wsm->keyData.clear();
        wsm->loc = DiskLoc();
        return Status::OK();
    }
Esempio n. 24
0
    Status ProjectionStage::transform(WorkingSetMember* member) {
        // The default no-fast-path case.
        if (ProjectionStageParams::NO_FAST_PATH == _projImpl) {
            return _exec->transform(member);
        }

        BSONObjBuilder bob;

        // Note that even if our fast path analysis is bug-free something that is
        // covered might be invalidated and just be an obj.  In this case we just go
        // through the SIMPLE_DOC path which is still correct if the covered data
        // is not available.
        //
        // SIMPLE_DOC implies that we expect an object so it's kind of redundant.
        if ((ProjectionStageParams::SIMPLE_DOC == _projImpl) || member->hasObj()) {
            // If we got here because of SIMPLE_DOC the planner shouldn't have messed up.
            invariant(member->hasObj());

            // Apply the SIMPLE_DOC projection.
            transformSimpleInclusion(member->obj.value(), _includedFields, bob);
        }
        else {
            invariant(ProjectionStageParams::COVERED_ONE_INDEX == _projImpl);
            // We're pulling data out of the key.
            invariant(1 == member->keyData.size());
            size_t keyIndex = 0;

            // Look at every key element...
            BSONObjIterator keyIterator(member->keyData[0].keyData);
            while (keyIterator.more()) {
                BSONElement elt = keyIterator.next();
                // If we're supposed to include it...
                if (_includeKey[keyIndex]) {
                    // Do so.
                    bob.appendAs(elt, _keyFieldNames[keyIndex]);
                }
                ++keyIndex;
            }
        }

        member->state = WorkingSetMember::OWNED_OBJ;
        member->keyData.clear();
        member->loc = RecordId();
        member->obj = Snapshotted<BSONObj>(SnapshotId(), bob.obj());
        return Status::OK();
    }
Message opCommandRequestFromOpMsgRequest(const OpMsgRequest& request) {
    const auto commandName = request.getCommandName();

    BufBuilder builder;
    builder.skip(mongo::MsgData::MsgDataHeaderSize);  // Leave room for message header.
    builder.appendStr(request.getDatabase());
    builder.appendStr(commandName);

    // OP_COMMAND is only used when communicating with 3.4 nodes and they serialize their metadata
    // fields differently. In addition to field-level differences, some generic arguments are pulled
    // out to a metadata object, separate from the body. We do all down-conversion here so that the
    // rest of the code only has to deal with the current format.
    BSONObjBuilder metadataBuilder;  // Will be appended to the message after we finish the body.
    {
        BSONObjBuilder bodyBuilder(builder);
        for (auto elem : request.body) {
            const auto fieldName = elem.fieldNameStringData();
            if (fieldName == "$configServerState") {
                metadataBuilder.appendAs(elem, "configsvr");
            } else if (fieldName == "$readPreference") {
                BSONObjBuilder ssmBuilder(metadataBuilder.subobjStart("$ssm"));
                ssmBuilder.append(elem);
                ssmBuilder.append("$secondaryOk",
                                  uassertStatusOK(ReadPreferenceSetting::fromInnerBSON(elem))
                                      .canRunOnSecondary());
            } else if (fieldName == "$db") {
                // skip
            } else if (fieldGoesInMetadata(commandName, fieldName)) {
                metadataBuilder.append(elem);
            } else {
                bodyBuilder.append(elem);
            }
        }
        for (auto&& seq : request.sequences) {
            invariant(seq.name.find('.') == std::string::npos);  // Only support top-level for now.
            dassert(!bodyBuilder.asTempObj().hasField(seq.name));
            bodyBuilder.append(seq.name, seq.objs);
        }
    }
    metadataBuilder.obj().appendSelfToBufBuilder(builder);

    MsgData::View msg = builder.buf();
    msg.setLen(builder.len());
    msg.setOperation(dbCommand);
    return Message(builder.release());
}
Esempio n. 26
0
 BSONObj BSONObj::replaceFieldNames( const BSONObj &names ) const {
     BSONObjBuilder b;
     BSONObjIterator i( *this );
     BSONObjIterator j( names );
     BSONElement f = j.more() ? j.next() : BSONObj().firstElement();
     while( i.more() ) {
         BSONElement e = i.next();
         if ( e.eoo() )
             break;
         if ( !f.eoo() ) {
             b.appendAs( e, f.fieldName() );
             f = j.next();
         } else {
             b.append( e );
         }
     }
     return b.obj();
 }
    BSONObj BatchedCommandResponse::toBSON() const {
        BSONObjBuilder builder;

        if (_isOkSet) builder.append(ok(), _ok);

        if (_isErrCodeSet) builder.append(errCode(), _errCode);

        if (_isErrInfoSet) builder.append(errInfo(), _errInfo);

        if (_isErrMessageSet) builder.append(errMessage(), _errMessage);

        if (_isNSet) builder.appendNumber(n(), _n);

        // We're using the BSONObj to store the _id value.
        if (_isSingleUpsertedSet) {
            builder.appendAs(_singleUpserted.firstElement(), singleUpserted());
        }

        if (_upsertDetails.get()) {
            BSONArrayBuilder upsertedBuilder(builder.subarrayStart(upsertDetails()));
            for (std::vector<BatchedUpsertDetail*>::const_iterator it = _upsertDetails->begin();
                 it != _upsertDetails->end();
                 ++it) {
                BSONObj upsertedDetailsDocument = (*it)->toBSON();
                upsertedBuilder.append(upsertedDetailsDocument);
            }
            upsertedBuilder.done();
        }

        if (_isLastOpSet) builder.append(lastOp(), _lastOp);

        if (_errDetails.get()) {
            BSONArrayBuilder errDetailsBuilder(builder.subarrayStart(errDetails()));
            for (std::vector<BatchedErrorDetail*>::const_iterator it = _errDetails->begin();
                 it != _errDetails->end();
                 ++it) {
                BSONObj errDetailsDocument = (*it)->toBSON();
                errDetailsBuilder.append(errDetailsDocument);
            }
            errDetailsBuilder.done();
        }

        return builder.obj();
    }
Esempio n. 28
0
    //b will be the value part of an array-typed BSONElement
    void Projection::appendArray( BSONObjBuilder& b , const BSONObj& a , bool nested) const {
        int skip  = nested ?  0 : _skip;
        int limit = nested ? -1 : _limit;

        if (skip < 0) {
            skip = max(0, skip + a.nFields());
        }

        int i=0;
        BSONObjIterator it(a);
        while (it.more()) {
            BSONElement e = it.next();

            if (skip) {
                skip--;
                continue;
            }

            if (limit != -1 && (limit-- == 0)) {
                break;
            }

            switch(e.type()) {
            case Array: {
                BSONObjBuilder subb;
                appendArray(subb , e.embeddedObject(), true);
                b.appendArray(b.numStr(i++), subb.obj());
                break;
            }
            case Object: {
                BSONObjBuilder subb;
                BSONObjIterator jt(e.embeddedObject());
                while (jt.more()) {
                    append(subb , jt.next());
                }
                b.append(b.numStr(i++), subb.obj());
                break;
            }
            default:
                if (_include)
                    b.appendAs(e, b.numStr(i++));
            }
        }
    }
Esempio n. 29
0
        /* CmdObj has the form {"hash" : <thingToHash>}
         * or {"hash" : <thingToHash>, "seed" : <number> }
         * Result has the form
         * {"key" : <thingTohash>, "seed" : <int>, "out": NumberLong(<hash>)}
         *
         * Example use in the shell:
         *> db.runCommand({hash: "hashthis", seed: 1})
         *> {"key" : "hashthis",
         *>  "seed" : 1,
         *>  "out" : NumberLong(6271151123721111923),
         *>  "ok" : 1 }
         **/
        bool run(OperationContext* txn, const string& db,
                  BSONObj& cmdObj,
                  int options, string& errmsg,
                  BSONObjBuilder& result){
            result.appendAs(cmdObj.firstElement(),"key");

            int seed = 0;
            if (cmdObj.hasField("seed")){
                if (! cmdObj["seed"].isNumber()) {
                    errmsg += "seed must be a number";
                    return false;
                }
                seed = cmdObj["seed"].numberInt();
            }
            result.append( "seed" , seed );

            result.append( "out" , BSONElementHasher::hash64( cmdObj.firstElement() , seed ) );
            return true;
        }
Esempio n. 30
0
 // elements is a non-geo field.  Add the values literally, expanding arrays.
 void getLiteralKeys(const BSONElementSet &elements, BSONObjSet *out) const {
     if (0 == elements.size()) {
         BSONObjBuilder b;
         b.appendNull("");
         out->insert(b.obj());
     } else if (1 == elements.size()) {
         BSONObjBuilder b;
         b.appendAs(*elements.begin(), "");
         out->insert(b.obj());
     } else {
         BSONArrayBuilder aBuilder;
         for (BSONElementSet::iterator i = elements.begin(); i != elements.end(); ++i) {
             aBuilder.append(*i);
         }
         BSONObjBuilder b;
         b.append("", aBuilder.arr());
         out->insert(b.obj());
     }
 }