mongodb源码分析(四)

 

mongodb源码分析(十)数据的插入

  本文我们分析mongodb中数据的插入流程.插入的简单流程可以归结于如下:

1. 如果存在对应collection则从collection中分配空间,然后将数据保存到分配的空间中,不存在则先从database中分配对应的collection,若database不存在则分配database,建立xx.ns和xx.0 等文件.

2. 根据插入数据更新collection中的索引.

下面来看代码,根据前面的分析我们知道插入操作的入口函数为:receivedInsert.

[cpp]  view plain copy
  1. void receivedInsert(Message& m, CurOp& op) {  
  2.     BSONObj first = d.nextJsObj();  
  3.     vector<BSONObj> multi;  
  4.     while (d.moreJSObjs()){//批量数据的插入  
  5.         if (multi.empty()) // first pass  
  6.             multi.push_back(first);  
  7.         multi.push_back( d.nextJsObj() );  
  8.     }  
  9.     while ( true ) {  
  10.             Lock::DBWrite lk(ns);  
  11.             if ( handlePossibleShardedMessage( m , 0 ) )  
  12.                 return;  
  13.             Client::Context ctx(ns);  
  14.             if( !multi.empty() ) {  
  15.                 const bool keepGoing = d.reservedField() & InsertOption_ContinueOnError;  
  16.                 insertMulti(keepGoing, ns, multi);//循环调用checkAndInsert做插入操作,keepGoing为true表示当插入操作错误时继续进行插入操作,否则终止插入操作  
  17.                 return;  
  18.             }  
  19.             checkAndInsert(ns, first);  
  20.             globalOpCounters.incInsertInWriteLock(1);  
  21.             return;  
  22.         }  
  23.     }  
  24. }  
[cpp]  view plain copy
  1. void checkAndInsert(const char *ns, /*modifies*/BSONObj& js) {   
  2.     uassert( 10059 , "object to insert too large", js.objsize() <= BSONObjMaxUserSize);//单条doc超过BSONObjMaxUserSize的不允许插入,可以通过修改代码的方式调整这个值  
  3.     {  
  4.         // check no $ modifiers.  note we only check top level.  (scanning deep would be quite expensive)  
  5.         BSONObjIterator i( js );//field中不允许以'$'开始  
  6.         while ( i.more() ) {  
  7.             BSONElement e = i.next();  
  8.             uassert( 13511 , "document to insert can't have $ fields" , e.fieldName()[0] != '$' );  
  9.         }  
  10.     }  
  11.     theDataFileMgr.insertWithObjMod(ns, js, false); // js may be modified in the call to add an _id field.  
  12.     logOp("i", ns, js);//为master/slave或者replset记录操作.  
  13. }  
[cpp]  view plain copy
  1. DiskLoc DataFileMgr::insertWithObjMod(const char *ns, BSONObj &o, bool god) {  
  2.     bool addedID = false;  
  3.     DiskLoc loc = insert( ns, o.objdata(), o.objsize(), god, true, &addedID );  
  4.     if( addedID && !loc.isNull() )  
  5.         o = BSONObj::make( loc.rec() );  
  6.     return loc;  
  7. }  
insert是mongodb数据的插入操作,其中包括了普通数据和索引数据的插入,下面的代码中大家将看到.

[cpp]  view plain copy
  1. DiskLoc DataFileMgr::insert(const char *ns, const void *obuf, int len, bool god, bool mayAddIndex, bool *addedID) {  
  2.     bool wouldAddIndex = false;  
  3.     {  
  4.         const char *sys = strstr(ns, "system.");  
  5.         if ( sys && !insert_checkSys(sys, ns, wouldAddIndex, obuf, god) )  
  6.             return DiskLoc();  
  7.     }  
  8.     bool addIndex = wouldAddIndex && mayAddIndex;//这是插入index的操作  
  9.     NamespaceDetails *d = nsdetails(ns);  
  10.     if ( d == 0 ) {//当前collection并不存在,首先分配一个collection,具体操作时根据插入的数据分配一个extent,分配一个namespacedetails,并且根据记录该namespacedetails.god为false则创建一个_id的索引,将该collection记录到system.namespaces collection中  
  11.         d = insert_newNamespace(ns, len, god);  
  12.     }  
  13.     NamespaceDetails *tableToIndex = 0;  
  14.     string tabletoidxns;  
  15.     BSONObj fixedIndexObject;  
  16.     if ( addIndex ) {//插入index的操作,如db.coll.ensureIndex({x:1})就是走这里的流程  
  17.         verify( obuf );  
  18.         BSONObj io((const char *) obuf);  
  19.         if( !prepareToBuildIndex(io, god, tabletoidxns, tableToIndex, fixedIndexObject ) ) {  
  20.             // prepare creates _id itself, or this indicates to fail the build silently (such   
  21.             // as if index already exists)  
  22.             return DiskLoc();  
  23.         }  
  24.         if ( ! fixedIndexObject.isEmpty() ) {  
  25.             obuf = fixedIndexObject.objdata();  
  26.             len = fixedIndexObject.objsize();  
  27.         }  
  28.     }  
  29.     int addID = 0; // 0 if not adding _id; if adding, the length of that new element  
  30.     if( !god ) {//没有_id数据则生成一个_id  
  31.         /* Check if we have an _id field. If we don't, we'll add it. 
  32.            Note that btree buckets which we insert aren't BSONObj's, but in that case god==true. 
  33.         */  
  34.         BSONObj io((const char *) obuf);  
  35.         BSONElement idField = io.getField( "_id" );  
  36.         uassert( 10099 ,  "_id cannot be an array", idField.type() != Array );  
  37.         // we don't add _id for capped collections in local as they don't have an _id index  
  38.         if( idField.eoo() && !wouldAddIndex &&  
  39.             !str::equals( nsToDatabase( ns ).c_str() , "local" ) && d->haveIdIndex() ) {  
  40.             if( addedID )  
  41.                 *addedID = true;  
  42.             addID = len;  
  43.             idToInsert_.oid.init();  
  44.             len += idToInsert.size();  
  45.         }  
  46.         BSONElementManipulator::lookForTimestamps( io );  
  47.     }  
  48.     int lenWHdr = d->getRecordAllocationSize( len + Record::HeaderSize );//得到分配数据的大小,这个大小值取决于是否设置了Flag_UsePowerOf2Sizes,设置了则分配的数据始终为2的n次方,可通过db.coll.runCommand({collMod:"coll","usePowerOf2Sizes":true})设置,没设置这个标志位就是需要分配的空间乘以paddingfactor,这个值会动态调整,最小为1,最大为2.具体会根据更新数据时是否原doc长度不够来调整.  
  49.   
  50.     // If the collection is capped, check if the new object will violate a unique index  
  51.     // constraint before allocating space.  
  52.     if ( d->nIndexes && d->isCapped() && !god ) {//唯一性检查,如果创建索引时指定了unique为true.  
  53.         checkNoIndexConflicts( d, BSONObj( reinterpret_cast<const char *>( obuf ) ) );  
  54.     }  
  55.     bool earlyIndex = true;  
  56.     DiskLoc loc;  
  57.     if( addID || tableToIndex || d->isCapped() ) {  
  58.         // if need id, we don't do the early indexing. this is not the common case so that is sort of ok  
  59.         earlyIndex = false;//实际的空间分配,分配的原理见<a href="http://blog.csdn.net/yhjj0108/article/details/8278041">http://blog.csdn.net/yhjj0108/article/details/8278041</a>  
  60.         loc = allocateSpaceForANewRecord(ns, d, lenWHdr, god);  
  61.     }  
  62.     else {  
  63.         loc = d->allocWillBeAt(ns, lenWHdr);  
  64.         if( loc.isNull() ) {  
  65.             // need to get a new extent so we have to do the true alloc now (not common case)  
  66.             earlyIndex = false;  
  67.             loc = allocateSpaceForANewRecord(ns, d, lenWHdr, god);  
  68.         }  
  69.     }  
  70.     if ( loc.isNull() ) {  
  71.         log() << "insert: couldn't alloc space for object ns:" << ns << " capped:" << d->isCapped() << endl;  
  72.         verify(d->isCapped());  
  73.         return DiskLoc();  
  74.     }  
  75.     if( earlyIndex ) {   
  76.         // add record to indexes using two step method so we can do the reading outside a write lock  
  77.         if ( d->nIndexes ) {  
  78.             verify( obuf );  
  79.             BSONObj obj((const char *) obuf);  
  80.             try {//从要插入的数据obj中取出所有collection中的field,然后将其插入到相应的索引Btree中  
  81.                 indexRecordUsingTwoSteps(ns, d, obj, loc, true);  
  82.             }  
  83.             catch( AssertionException& ) {  
  84.                 // should be a dup key error on _id index  
  85.                 dassert( !tableToIndex && !d->isCapped() );  
  86.                 // no need to delete/rollback the record as it was not added yet  
  87.                 throw;  
  88.             }  
  89.         }  
  90.         // really allocate now  
  91.         DiskLoc real = allocateSpaceForANewRecord(ns, d, lenWHdr, god);  
  92.         verify( real == loc );  
  93.     }  
  94.     Record *r = loc.rec();  
  95.     {//将实际的数据复制到空间中  
  96.         verify( r->lengthWithHeaders() >= lenWHdr );  
  97.         r = (Record*) getDur().writingPtr(r, lenWHdr);  
  98.         if( addID ) {  
  99.             /* a little effort was made here to avoid a double copy when we add an ID */  
  100.             ((int&)*r->data()) = *((int*) obuf) + idToInsert.size();  
  101.             memcpy(r->data()+4, idToInsert.rawdata(), idToInsert.size());  
  102.             memcpy(r->data()+4+idToInsert.size(), ((char *)obuf)+4, addID-4);  
  103.         }  
  104.         else {  
  105.             if( obuf ) // obuf can be null from internal callers  
  106.                 memcpy(r->data(), obuf, len);  
  107.         }  
  108.     }  
  109.     addRecordToRecListInExtent(r, loc);//更新extent链表信息  
  110.     /* durability todo : this could be a bit annoying / slow to record constantly */  
  111.     {  
  112.         NamespaceDetails::Stats *s = getDur().writing(&d->stats);  
  113.         s->datasize += r->netLength();  
  114.         s->nrecords++;  
  115.     }  
  116.     // we don't bother resetting query optimizer stats for the god tables - also god is true when adding a btree bucket  
  117.     if ( !god )  
  118.         NamespaceDetailsTransient::get( ns ).notifyOfWriteOp();  
  119.     if ( tableToIndex ) {//新添加了一个索引,这里将建立具体的索引信息  
  120.         insert_makeIndex(tableToIndex, tabletoidxns, loc);  
  121.     }  
  122.     /* add this record to our indexes */  
  123.     if ( !earlyIndex && d->nIndexes ) {  
  124.             BSONObj obj(r->data());  
  125.             // not sure which of these is better -- either can be used.  oldIndexRecord may be faster,   
  126.             // but twosteps handles dup key errors more efficiently.  
  127.             //oldIndexRecord(d, obj, loc);  
  128.             indexRecordUsingTwoSteps(ns, d, obj, loc, false);  
  129.     }  
  130.     d->paddingFits();  
  131.     return loc;  
  132. }  
下面来看看2步索引插入indexRecordUsingTwoSteps函数
[cpp]  view plain copy
  1. void indexRecordUsingTwoSteps(const char *ns, NamespaceDetails *d, BSONObj obj,  
  2.                                      DiskLoc loc, bool shouldBeUnlocked) {  
  3.     vector<int> multi;  
  4.     vector<BSONObjSet> multiKeys;  
  5.     IndexInterface::IndexInserter inserter;  
  6.     // Step 1, read phase.  
  7.     int n = d->nIndexesBeingBuilt();//插入索引的动作比如说有索引{x:1},则取出插入的数据如  
  8.     {//{x:1,y:1},这里取出1这个数据插入到btree索引中对于比较复杂的multikey索引如插入数据  
  9.         BSONObjSet keys;//为{x:[1,2,3,4,5]},则分别取出1,2,3,4,5插入到btree中并把索引x标为multikey索引  
  10.         for ( int i = 0; i < n; i++ ) {//这些需要注意的是当从obj中取出的值为空时如果索引不为sparse,则将key设置为nullkey  
  11.             // this call throws on unique constraint violation.  we haven't done any writes yet so that is fine.  
  12.             fetchIndexInserters(/*out*/keys, inserter, d, i, obj, loc);//这里就是从obj中取出索引域的值,然后造出该值应该插入到索引的位置  
  13.             if( keys.size() > 1 ) {//多值索引  
  14.                 multi.push_back(i);  
  15.                 multiKeys.push_back(BSONObjSet());  
  16.                 multiKeys[multiKeys.size()-1].swap(keys);  
  17.             }  
  18.             keys.clear();  
  19.         }  
  20.     }//完成具体的插入动作  
  21.     inserter.finishAllInsertions();  // Step 2, write phase.  
  22.     // now finish adding multikeys  
  23.     for( unsigned j = 0; j < multi.size(); j++ ) {//多值索引的插入部分  
  24.         unsigned i = multi[j];  
  25.         BSONObjSet& keys = multiKeys[j];  
  26.         IndexDetails& idx = d->idx(i);  
  27.         IndexInterface& ii = idx.idxInterface();  
  28.         Ordering ordering = Ordering::make(idx.keyPattern());  
  29.         d->setIndexIsMultikey(ns, i);//将该索引标识为多值索引  
  30.         for( BSONObjSet::iterator k = ++keys.begin()/*skip 1*/; k != keys.end(); k++ ) {  
  31.             try {  
  32.                 ii.bt_insert(idx.head, loc, *k, ordering, !idx.unique(), idx);  
  33.             } catch (AssertionException& e) {  
  34.                 if( e.getCode() == 10287 && (int) i == d->nIndexes ) {  
  35.                     DEV log() << "info: caught key already in index on bg indexing (ok)" << endl;  
  36.                 }  
  37.                 else {  
  38.                     /* roll back previously added index entries 
  39.                        note must do self index as it is multikey and could require some cleanup itself 
  40.                     */  
  41.                     forint j = 0; j < n; j++ ) {  
  42.                         try {  
  43.                             _unindexRecord(d->idx(j), obj, loc, false);  
  44.                         }  
  45.                         catch(...) {  
  46.                             log(3) << "unindex fails on rollback after unique key constraint prevented insert\n";  
  47.                         }  
  48.                     }  
  49.                     throw;  
  50.                 }  
  51.             }  
  52.         }  
  53.     }  
  54. }  
最后来看看insert_makeIndex.

[cpp]  view plain copy
  1. void NOINLINE_DECL insert_makeIndex(NamespaceDetails *tableToIndex, const string& tabletoidxns, const DiskLoc& loc) {   
  2.     BSONObj info = loc.obj();  
  3.     bool background = info["background"].trueValue();  
  4.     if( background && cc().isSyncThread() ) {  
  5.         /* don't do background indexing on slaves.  there are nuances.  this could be added later 
  6.             but requires more code. 
  7.             */  
  8.         log() << "info: indexing in foreground on this replica; was a background index build on the primary" << endl;  
  9.         background = false;  
  10.     }  
  11.     int idxNo = tableToIndex->nIndexes;//添加索引结构到namespacedetail或者namespacedetail::extra中  
  12.     IndexDetails& idx = tableToIndex->addIndex(tabletoidxns.c_str(), !background); // clear transient info caches so they refresh; increments nIndexes  
  13.     getDur().writingDiskLoc(idx.info) = loc;  
  14.     try {//根据新创建的索引快速建立该collection的索引  
  15.         buildAnIndex(tabletoidxns, tableToIndex, idx, idxNo, background);  
  16.     }  
  17. }  
insert_makeIndex->buildAnIndex

[cpp]  view plain copy
  1. void buildAnIndex(string ns, NamespaceDetails *d, IndexDetails& idx, int idxNo, bool background) {  
  2.     if( inDBRepair || !background ) {//同步建立索引  
  3.         n = fastBuildIndex(ns.c_str(), d, idx, idxNo);  
  4.         verify( !idx.head.isNull() );  
  5.     }  
  6.     else {//开启一个线程来建立索引  
  7.         BackgroundIndexBuildJob j(ns.c_str());  
  8.         n = j.go(ns, d, idx, idxNo);  
  9.     }  
  10. }  
insert_makeIndex->buildAnIndex->fastBuildIndex

[cpp]  view plain copy
  1. unsigned long long fastBuildIndex(const char *ns, NamespaceDetails *d, IndexDetails& idx, int idxNo) {  
  2.     CurOp * op = cc().curop();  
  3.     bool dupsAllowed = !idx.unique();  
  4.     bool dropDups = idx.dropDups() || inDBRepair;  
  5.     BSONObj order = idx.keyPattern();  
  6.     getDur().writingDiskLoc(idx.head).Null();  
  7.     /* get and sort all the keys ----- */  
  8.     ProgressMeterHolder pm( op->setMessage( "index: (1/3) external sort" , d->stats.nrecords , 10 ) );  
  9.     SortPhaseOne _ours;  
  10.     SortPhaseOne *phase1 = precalced;  
  11.     if( phase1 == 0 ) {  
  12.         phase1 = &_ours;  
  13.         SortPhaseOne& p1 = *phase1;  
  14.         shared_ptr<Cursor> c = theDataFileMgr.findAll(ns);  
  15.         p1.sorter.reset( new BSONObjExternalSorter(idx.idxInterface(), order) );  
  16.         p1.sorter->hintNumObjects( d->stats.nrecords );  
  17.         const IndexSpec& spec = idx.getSpec();  
  18.         while ( c->ok() ) {//每读出1000条索引使用快排对其排序,然后输出到一个文件中  
  19.             BSONObj o = c->current();//记录文件句柄  
  20.             DiskLoc loc = c->currLoc();  
  21.             p1.addKeys(spec, o, loc);  
  22.             c->advance();  
  23.             pm.hit();  
  24.             if ( logLevel > 1 && p1.n % 10000 == 0 ) {  
  25.                 printMemInfo( "\t iterating objects" );  
  26.             }  
  27.         };  
  28.     }  
  29.     pm.finished();  
  30.     BSONObjExternalSorter& sorter = *(phase1->sorter);  
  31.     // Ensure the index and external sorter have a consistent index interface (and sort order).  
  32.     fassert( 16408, &idx.idxInterface() == &sorter.getIndexInterface() );  
  33.     if( phase1->multi )//multi索引  
  34.         d->setIndexIsMultikey(ns, idxNo);  
  35.     if ( logLevel > 1 ) printMemInfo( "before final sort" );  
  36.     phase1->sorter->sort();  
  37.     if ( logLevel > 1 ) printMemInfo( "after final sort" );  
  38.     log(t.seconds() > 5 ? 0 : 1) << "\t external sort used : " << sorter.numFiles() << " files " << " in " << t.seconds() << " secs" << endl;  
  39.     set<DiskLoc> dupsToDrop;  
  40.     /* build index --- */  
  41.     if( idx.version() == 0 )//mongodb有两种索引,V0和V1,其中目前使用V1,10gen称V1索引比V0小25%的空间,V0是为了兼容2.0以前版本的系统,目前默认使用V1  
  42.         buildBottomUpPhases2And3<V0>(dupsAllowed, idx, sorter, dropDups, dupsToDrop, op, phase1, pm, t);  
  43.     else if( idx.version() == 1 ) //从sorter中读出输入并且将其插入到索引btree中,因为之前排过序,这里只需要顺序读出并做插入操作就行  
  44.         buildBottomUpPhases2And3<V1>(dupsAllowed, idx, sorter, dropDups, dupsToDrop, op, phase1, pm, t);  
  45.     else  
  46.         verify(false);  
  47.     if( dropDups ) //设置了unique且数据有重复,将重复的数据删除  
  48.         log() << "\t fastBuildIndex dupsToDrop:" << dupsToDrop.size() << endl;  
  49.     for( set<DiskLoc>::iterator i = dupsToDrop.begin(); i != dupsToDrop.end(); i++ ){  
  50.         theDataFileMgr.deleteRecord( ns, i->rec(), *i, false /* cappedOk */ , true /* noWarn */ , isMaster( ns ) /* logOp */ );  
  51.         getDur().commitIfNeeded();  
  52.     }  
  53.     return phase1->n;  
  54. }  
        这里所有的关于数据的插入操作讲解完毕,流程很简单,比上查询操作来说太简单了.需要注意

的是sparse索引和索引的建立,当已存储数据是建立索引为unique时重复的数据都会被删除.


原文链接:mongodb源码分析(十)数据的插入

作者: yhjj0108,杨浩


  本文我们将删除,删除操作概括起来就是遍历将collection中数据对应的索引删除,然后是删除数据,最后将删除

的空间加入到之前文章描述的deletelist中.下面我们来看具体的代码吧.删除的入口是receiveDelete函数.

[cpp]  view plain copy
  1. void receivedDelete(Message& m, CurOp& op) {  
  2.     DbMessage d(m);  
  3.     const char *ns = d.getns();  
  4.     op.debug().ns = ns;  
  5.     int flags = d.pullInt();  
  6.     bool justOne = flags & RemoveOption_JustOne;//值删除单条doc  
  7.     bool broadcast = flags & RemoveOption_Broadcast;  
  8.     verify( d.moreJSObjs() );  
  9.     BSONObj pattern = d.nextJsObj();  
  10.     op.debug().query = pattern;  
  11.     op.setQuery(pattern);  
  12.     PageFaultRetryableSection s;  
  13.     while ( 1 ) {  
  14.         try {  
  15.             Lock::DBWrite lk(ns);  
  16.             // writelock is used to synchronize stepdowns w/ writes  
  17.             uassert( 10056 ,  "not master", isMasterNs( ns ) );  
  18.             // if this ever moves to outside of lock, need to adjust check Client::Context::_finishInit  
  19.             if ( ! broadcast && handlePossibleShardedMessage( m , 0 ) )  
  20.                 return;  
  21.             Client::Context ctx(ns);//具体的删除函数  
  22.             long long n = deleteObjects(ns, pattern, justOne, true);  
  23.             lastError.getSafe()->recordDelete( n );  
  24.             break;  
  25.         }  
  26.         catch ( PageFaultException& e ) {  
  27.             LOG(2) << "recordDelete got a PageFaultException" << endl;  
  28.             e.touch();  
  29.         }  
  30.     }  
  31. }  
receiveDelete->deleteObjects

[cpp]  view plain copy
  1. long long deleteObjects(const char *ns, BSONObj pattern, bool justOne, bool logop, bool god, RemoveSaver * rs ) {  
  2.     long long nDeleted = 0;//根据查询条件得到游标  
  3.     shared_ptr< Cursor > creal = NamespaceDetailsTransient::getCursor( ns, pattern );  
  4.     if( !creal->ok() )  
  5.         return nDeleted;  
  6.     shared_ptr< Cursor > cPtr = creal;  
  7.     auto_ptr<ClientCursor> cc( new ClientCursor( QueryOption_NoCursorTimeout, cPtr, ns) );  
  8.     cc->setDoingDeletes( true );  
  9.     CursorId id = cc->cursorid();  
  10.     bool canYield = !god && !(creal->matcher() && creal->matcher()->docMatcher().atomic());  
  11.     do {  
  12.         // TODO: we can generalize this I believe  
  13.         //         
  14.         bool willNeedRecord = (creal->matcher() && creal->matcher()->needRecord()) || pattern.isEmpty() || isSimpleIdQuery( pattern );  
  15.         if ( ! willNeedRecord ) {  
  16.             // TODO: this is a total hack right now  
  17.             // check if the index full encompasses query  
  18.             if ( pattern.nFields() == 1 &&   
  19.                  str::equals( pattern.firstElement().fieldName() , creal->indexKeyPattern().firstElement().fieldName() ) )  
  20.                 willNeedRecord = true;  
  21.         }  
  22.         if ( canYield && ! cc->yieldSometimes( willNeedRecord ? ClientCursor::WillNeed : ClientCursor::MaybeCovered ) ) {  
  23.             cc.release(); // has already been deleted elsewhere  
  24.             // TODO should we assert or something?  
  25.             break;  
  26.         }  
  27.         if ( !cc->ok() ) {  
  28.             break// if we yielded, could have hit the end  
  29.         }  
  30.         // this way we can avoid calling prepareToYield() every time (expensive)  
  31.         // as well as some other nuances handled  
  32.         cc->setDoingDeletes( true );  
  33.         DiskLoc rloc = cc->currLoc();  
  34.         BSONObj key = cc->currKey();  
  35.         bool match = creal->currentMatches();  
  36.         cc->advance();  
  37.         if ( ! match )  
  38.             continue;  
  39.         // SERVER-5198 Advance past the document to be modified, but see SERVER-5725.  
  40.         while( cc->ok() && rloc == cc->currLoc() ) {//多值索引就会出现这种状况,需要跳过同一条记录  
  41.             cc->advance();  
  42.         }  
  43.         bool foundAllResults = ( justOne || !cc->ok() );  
  44.         if ( !foundAllResults ) {  
  45.             // NOTE: Saving and restoring a btree cursor's position was historically described  
  46.             // as slow here.  
  47.             cc->c()->prepareToTouchEarlierIterate();  
  48.         }  
  49.         if ( logop ) {//记录删除动作  
  50.             BSONElement e;  
  51.             if( BSONObj::make( rloc.rec() ).getObjectID( e ) ) {  
  52.                 BSONObjBuilder b;  
  53.                 b.append( e );  
  54.                 bool replJustOne = true;  
  55.                 logOp( "d", ns, b.done(), 0, &replJustOne );  
  56.             }  
  57.             else {  
  58.                 problem() << "deleted object without id, not logging" << endl;  
  59.             }  
  60.         }  
  61.         if ( rs )//将要删除的doc记录下来  
  62.             rs->goingToDelete( rloc.obj() /*cc->c->current()*/ );  
  63.         theDataFileMgr.deleteRecord(ns, rloc.rec(), rloc);//记录的删除  
  64.         nDeleted++;  
  65.         if ( foundAllResults ) {  
  66.             break;  
  67.         }  
  68.         cc->c()->recoverFromTouchingEarlierIterate();  
  69.         if( !god )   
  70.             getDur().commitIfNeeded();  
  71.         if( debug && god && nDeleted == 100 )   
  72.             log() << "warning high number of deletes with god=true which could use significant memory" << endl;  
  73.     }  
  74.     while ( cc->ok() );  
  75.     if ( cc.get() && ClientCursor::find( id , false ) == 0 ) {  
  76.         // TODO: remove this and the id declaration above if this doesn't trigger  
  77.         //       if it does, then i'm very confused (ERH 06/2011)  
  78.         error() << "this should be impossible" << endl;  
  79.         printStackTrace();  
  80.         cc.release();  
  81.     }  
  82.     return nDeleted;  
  83. }  

receiveDelete->deleteObjects->deleteRecord

[cpp]  view plain copy
  1. void DataFileMgr::deleteRecord(const char *ns, Record *todelete, const DiskLoc& dl, bool cappedOK, bool noWarn, bool doLog ) {  
  2.     NamespaceDetails* d = nsdetails(ns);  
  3.     if ( d->isCapped() && !cappedOK ) {  
  4.         out() << "failing remove on a capped ns " << ns << endl;  
  5.         uassert( 10089 ,  "can't remove from a capped collection" , 0 );  
  6.         return;  
  7.     }  
  8.     BSONObj toDelete;  
  9.     if ( doLog ) {  
  10.         BSONElement e = dl.obj()["_id"];  
  11.         if ( e.type() ) {  
  12.             toDelete = e.wrap();  
  13.         }  
  14.     }  
  15.     /* check if any cursors point to us.  if so, advance them. */  
  16.     ClientCursor::aboutToDelete(dl);  
  17.     unindexRecord(d, todelete, dl, noWarn);//删除索引,循环删除所有索引中记录todelete的部分.  
  18.     _deleteRecord(d, ns, todelete, dl);//实际的数据删除并将其空间添加到deletedList中  
  19.     NamespaceDetailsTransient::get( ns ).notifyOfWriteOp();  
  20.     if ( ! toDelete.isEmpty() ) {  
  21.         logOp( "d" , ns , toDelete );  
  22.     }  
  23. }  
         到这里删除过程结束,可见这部分流程是很简单的.


原文链接: mongodb源码分析(十一)数据的删除

作者: yhjj0108,杨浩


相对于删除操作,更新操作复杂得多,因为其操作很多,mongodb提供了很多更新的操作符,另外还要考虑到更

新时如果原来的数据doc空间不够还得删除原来的doc再添加新的doc,相当于做了两次操作,这里的过程同样会影

响collection中所有的索引.下面来看代码吧,更新操作的入口为:

[cpp]  view plain copy
  1. void receivedUpdate(Message& m, CurOp& op) {  
  2.     DbMessage d(m);  
  3.     const char *ns = d.getns();  
  4.     op.debug().ns = ns;  
  5.     int flags = d.pullInt();  
  6.     BSONObj query = d.nextJsObj();  
  7.     BSONObj toupdate = d.nextJsObj();  
  8.     bool upsert = flags & UpdateOption_Upsert;  
  9.     bool multi = flags & UpdateOption_Multi;  
  10.     bool broadcast = flags & UpdateOption_Broadcast;  
  11.     op.debug().query = query;  
  12.     op.setQuery(query);  
  13.     PageFaultRetryableSection s;  
  14.     while ( 1 ) {  
  15.         try {  
  16.             Lock::DBWrite lk(ns);                  
  17.             // void ReplSetImpl::relinquish() uses big write lock so   
  18.             // this is thus synchronized given our lock above.  
  19.             uassert( 10054 ,  "not master", isMasterNs( ns ) );//不是master不能执行更新  
  20.             // if this ever moves to outside of lock, need to adjust check Client::Context::_finishInit  
  21.             if ( ! broadcast && handlePossibleShardedMessage( m , 0 ) )  
  22.                 return;  
  23.             Client::Context ctx( ns );//实际的更新部分  
  24.             UpdateResult res = updateObjects(ns, toupdate, query, upsert, multi, true, op.debug() );  
  25.             lastError.getSafe()->recordUpdate( res.existing , res.num , res.upserted ); // for getlasterror  
  26.             break;  
  27.         }  
  28.         catch ( PageFaultException& e ) {//要更新的数据不在内存,让操作系统加载其到内存  
  29.             e.touch();  
  30.         }  
  31.     }  
  32. }  
        updateObjects做了基本的检查后直接调用了_updateObjects,所以跳过updateObjects函数

直接分析_updateObjects. receiveUpdate->updateObjects->_updateObjects.

[cpp]  view plain copy
  1.  UpdateResult _updateObjects( bool su,const char* ns,const BSONObj& updateobj,const BSONObj& patternOrig,bool upsert,  
  2.                               bool multi,bool logop ,OpDebug& debug,RemoveSaver* rs,bool fromMigrate,const QueryPlanSelectionPolicy& planPolicy ) {  
  3.      Client& client = cc();  
  4.      int profile = client.database()->profile;  
  5.      debug.updateobj = updateobj;  
  6.      // The idea with these here it to make them loop invariant for  
  7.      // multi updates, and thus be a bit faster for that case.  The  
  8.      // pointers may be left invalid on a failed or terminal yield  
  9.      // recovery.  
  10.      NamespaceDetails* d = nsdetails(ns); // can be null if an upsert...  
  11.      NamespaceDetailsTransient* nsdt = &NamespaceDetailsTransient::get(ns);  
  12.      auto_ptr<ModSet> mods;  
  13.      bool isOperatorUpdate = updateobj.firstElementFieldName()[0] == '$';  
  14.      int modsIsIndexed = false// really the # of indexes  
  15.      if ( isOperatorUpdate ) {//根据更新操作提取具体的更新符以及数据建立更新操作结构,比如update={$set:{a:1},$inc{b:1}}  
  16.          if( d && d->indexBuildInProgress ) {//那么建立两个mod,第一个操作符为$set,操作对象为{a:1},第二个操作符为$inc,  
  17.              set<string> bgKeys;             //操作对象为{b:1}   
  18.              d->inProgIdx().keyPattern().getFieldNames(bgKeys);  
  19.              mods.reset( new ModSet(updateobj, nsdt->indexKeys(), &bgKeys) );  
  20.          }  
  21.          else {  
  22.              mods.reset( new ModSet(updateobj, nsdt->indexKeys()) );  
  23.          }  
  24.          modsIsIndexed = mods->isIndexed();//修改可能变更到索引,后面则需要同时更新索引才行  
  25.      }  
  26. 单id查询的更新比如说pattern={_id:1},updateobj={$inc:{x:1}},并且这里x不为索引  
  27.      if( planPolicy.permitOptimalIdPlan() && !multi && isSimpleIdQuery(patternOrig) && d &&  
  28.         !modsIsIndexed ) {  
  29.          int idxNo = d->findIdIndex();  
  30.          if( idxNo >= 0 ) {  
  31.              debug.idhack = true;//updateById函数和后面的操作流程差不多,这里就不分析了,看后面的分析  
  32.              UpdateResult result = _updateById( isOperatorUpdate,idxNo,mods.get(),profile,d,nsdt,su,ns,  
  33.                                                 updateobj,patternOrig,logop,debug,fromMigrate);  
  34.              if ( result.existing || ! upsert ) {  
  35.                  return result;  
  36.              }  
  37.              else if ( upsert && ! isOperatorUpdate && ! logop) {  
  38.                  // this handles repl inserts  
  39.                  checkNoMods( updateobj );  
  40.                  debug.upsert = true;  
  41.                  BSONObj no = updateobj;  
  42.                  theDataFileMgr.insertWithObjMod(ns, no, su);  
  43.                  return UpdateResult( 0 , 0 , 1 , no );  
  44.              }  
  45.          }  
  46.      }  
  47.      int numModded = 0;  
  48.      debug.nscanned = 0;  
  49.      shared_ptr<Cursor> c =  
  50.          NamespaceDetailsTransient::getCursor( ns, patternOrig, BSONObj(), planPolicy );  
  51.      d = nsdetails(ns);  
  52.      nsdt = &NamespaceDetailsTransient::get(ns);  
  53.      bool autoDedup = c->autoDedup();  
  54.      if( c->ok() ) {  
  55.          set<DiskLoc> seenObjects;  
  56.          MatchDetails details;  
  57.          auto_ptr<ClientCursor> cc;  
  58.          do {  
  59.              if ( cc.get() == 0 &&//抛出异常在外捕获让系统将数据加载进内存  
  60.                   client.allowedToThrowPageFaultException() &&  
  61.                   ! c->currLoc().isNull() &&  
  62.                   ! c->currLoc().rec()->likelyInPhysicalMemory() ) {  
  63.                  throw PageFaultException( c->currLoc().rec() );  
  64.              }  
  65.              debug.nscanned++;  
  66.              if ( mods.get() && mods->hasDynamicArray() ) {  
  67.                  // The Cursor must have a Matcher to record an elemMatchKey.  But currently  
  68.                  // a modifier on a dynamic array field may be applied even if there is no  
  69.                  // elemMatchKey, so a matcher cannot be required.  
  70.                  //verify( c->matcher() );  
  71.                  details.requestElemMatchKey();  
  72.              }  
  73.              if ( !c->currentMatches( &details ) ) {  
  74.                  c->advance();  
  75.                  continue;  
  76.              }  
  77.   //match  
  78.              Record* r = c->_current();  
  79.              DiskLoc loc = c->currLoc();  
  80.              if ( c->getsetdup( loc ) && autoDedup ) {//首先找到的loc肯定c->getsetdup()返回false,第二次  
  81.                  c->advance();//更新同样的内容时c->getsetdup返回true,这是由于muti index产生的  
  82.                  continue;//所以第二次要跳过这一条记录,这种情况不会出现于basicCursor,因为其总是返回false  
  83.              }  
  84.              BSONObj js = BSONObj::make(r);  
  85.              BSONObj pattern = patternOrig;  
  86.              /* look for $inc etc.  note as listed here, all fields to inc must be this type, you can't set some 
  87.                  regular ones at the moment. */  
  88.              if ( isOperatorUpdate ) {  
  89.                  if ( multi ) {  
  90.                      // go to next record in case this one moves  
  91.                      c->advance();  
  92.                      // Update operations are deduped for cursors that implement their own  
  93.                      // deduplication.  In particular, some geo cursors are excluded.  
  94.                      if ( autoDedup ) {  
  95.                          if ( seenObjects.count( loc ) ) {//判断这个loc是否已经存在,第一次肯定是  
  96.                              continue;//不存在的,所以总是返回false  
  97.                          }  
  98.                          // SERVER-5198 Advance past the document to be modified, provided  
  99.                          // deduplication is enabled, but see SERVER-5725.  
  100.                          while( c->ok() && loc == c->currLoc() ) {//如果遍历过程中始终指向了  
  101.                              c->advance();//该loc,则一直advance,直到跳过该loc  
  102.                          }  
  103.                      }  
  104.                  }  
  105.                  const BSONObj& onDisk = loc.obj();  
  106.                  ModSet* useMods = mods.get();  
  107.                  bool forceRewrite = false;  
  108. //需要说明的是这里的".$"符号只是替换为match时array当时的位置  
  109. //所以这里有一个问题,如果我有一条数据为{x:[1,2,3,4,5],y:[6,7,8,9,10]}  
  110. //当我调用update({x:1,y:9},{$inc:{x.$:1}},false,false)本意是更新x的第一个位置  
  111. //数据,但是实际上得到的结果是{x:[1,2,3,5,5],y:[6,7,8,9,10]},这算一个bug吗???  
  112.                  auto_ptr<ModSet> mymodset;//这里是存在着".$"符号  
  113.                  if ( details.hasElemMatchKey() && mods->hasDynamicArray() ) {  
  114.                      useMods = mods->fixDynamicArray( details.elemMatchKey() );//这里的elemMatchKey是在查询匹配时  
  115.                      mymodset.reset( useMods );//设置的,只是简单的将.$替换为elelMatchKey设置的位置  
  116.                      forceRewrite = true;  
  117.                  }//建立ModSetState,并且设置每一位更新数据是否可以通过简单替换来达到更新数据的目的如{$set:{a:10}}  
  118.                  auto_ptr<ModSetState> mss = useMods->prepare( onDisk );//若a本来存在只需要替换其值为10就行了,不涉及到多占内存的情况  
  119.                  bool willAdvanceCursor = multi && c->ok() && ( modsIsIndexed || ! mss->canApplyInPlace() );  
  120.                  if ( willAdvanceCursor ) {  
  121.                      if ( cc.get() ) {  
  122.                          cc->setDoingDeletes( true );  
  123.                      }  
  124.                      c->prepareToTouchEarlierIterate();  
  125.                  }  
  126.                  if ( modsIsIndexed <= 0 && mss->canApplyInPlace() ) {//可以直接替换,如上面举的例子  
  127.                      mss->applyModsInPlace( true );// const_cast<BSONObj&>(onDisk) );  
  128.                      if ( profile && !multi )  
  129.                          debug.fastmod = true;  
  130.                      if ( modsIsIndexed ) {  
  131.                          seenObjects.insert( loc );  
  132.                      }  
  133.                      d->paddingFits();  
  134.                  }  
  135.                  else {  
  136.                      if ( rs )  
  137.                          rs->goingToDelete( onDisk );//将要修改的部分转存到磁盘上  
  138.                      BSONObj newObj = mss->createNewFromMods();//要更新的obj不能通过简单的替换某个值来达到更新目的,必须得  
  139.                      checkTooLarge(newObj);//根据更新值和原来的值重新创建一个新的对象  
  140.                      DiskLoc newLoc = theDataFileMgr.updateRecord(ns,d,nsdt,r,loc,newObj.objdata(),newObj.objsize(),debug);  
  141.                      if ( newLoc != loc || modsIsIndexed ){  
  142.                          // log() << "Moved obj " << newLoc.obj()["_id"] << " from " << loc << " to " << newLoc << endl;  
  143.                          // object moved, need to make sure we don' get again  
  144.                          seenObjects.insert( newLoc );  
  145.                      }  
  146.                  }  
  147.                  numModded++;  
  148.                  if ( ! multi )  
  149.                      return UpdateResult( 1 , 1 , numModded , BSONObj() );  
  150.                  if ( willAdvanceCursor )  
  151.                      c->recoverFromTouchingEarlierIterate();  
  152.                  getDur().commitIfNeeded();  
  153.                  continue;  
  154.              }  
  155.              BSONElementManipulator::lookForTimestamps( updateobj );  
  156.              checkNoMods( updateobj );//无操作符数据的更新  
  157.              theDataFileMgr.updateRecord(ns, d, nsdt, r, loc , updateobj.objdata(), updateobj.objsize(), debug, su);  
  158.              return UpdateResult( 1 , 0 , 1 , BSONObj() );  
  159.          } while ( c->ok() );  
  160.      } // endif  
  161.      if ( numModded )  
  162.          return UpdateResult( 1 , 1 , numModded , BSONObj() );  
  163.      if ( upsert ) {//这里到了插入了,说明查询没查到数据,进入插入操作  
  164.          if ( updateobj.firstElementFieldName()[0] == '$' ) {  
  165.              // upsert of an $operation. build a default object  
  166.              BSONObj newObj = mods->createNewFromQuery( patternOrig );//根据查询语句创建一个obj  
  167.              checkNoMods( newObj );  
  168.              debug.fastmodinsert = true;  
  169.              theDataFileMgr.insertWithObjMod(ns, newObj, su);  
  170.              return UpdateResult( 0 , 1 , 1 , newObj );  
  171.          }  
  172.          checkNoMods( updateobj );  
  173.          debug.upsert = true;  
  174.          BSONObj no = updateobj;  
  175.          theDataFileMgr.insertWithObjMod(ns, no, su);  
  176.          return UpdateResult( 0 , 0 , 1 , no );  
  177.      }  
  178.      return UpdateResult( 0 , isOperatorUpdate , 0 , BSONObj() );  
  179.  }  
       上面的代码可知更新操作如果原对象与更新后的对象占用空间一致并且更新操作不会影响到索引

那么就执行简单的替换,否则就需要调用createNewFromMods函数创建出一个新的对象,并调用

updateRecord去更新实际的数据.下面来看看createNewFromMods函数.

[cpp]  view plain copy
  1. BSONObj ModSetState::createNewFromMods() {  
  2.     BSONObjBuilder b( (int)(_obj.objsize() * 1.1) );//很可能需要更多存储空间,初始化更大的空间  
  3.     createNewObjFromMods( "" , b , _obj );  
  4.     return _newFromMods = b.obj();  
  5. }  
[cpp]  view plain copy
  1. void ModSetState::createNewObjFromMods( const string& root,  
  2.                                         BSONObjBuilder& builder,  
  3.                                         const BSONObj& obj ) {  
  4.     BSONObjIteratorSorted es( obj );  
  5.     createNewFromMods( root, builder, es, modsForRoot( root ), LexNumCmp( true ) );  
  6. }  
[cpp]  view plain copy
  1. void ModSetState::createNewFromMods( const string& root,  
  2.                                      BSONBuilderBase& builder,  
  3.                                      BSONIteratorSorted& es,  
  4.                                      const ModStateRange& modRange,  
  5.                                      const LexNumCmp& lexNumCmp ) {  
  6.     ModStateHolder::iterator m = modRange.first;  
  7.     const ModStateHolder::const_iterator mend = modRange.second;  
  8.     BSONElement e = es.next();  
  9.     set<string> onedownseen;  
  10.     BSONElement prevE;  
  11.     while ( !e.eoo() && m != mend ) {  
  12.         if ( duplicateFieldName( prevE, e ) ) {//前一个没有匹配,说明这个域没有被更改到,直接添加到新的对象上  
  13.             // Just copy through an element with a duplicate field name.  
  14.             builder.append( e );  
  15.             prevE = e;  
  16.             e = es.next();  
  17.             continue;  
  18.         }  
  19.         prevE = e;  
  20.         string field = root + e.fieldName();  
  21.         FieldCompareResult cmp = compareDottedFieldNames( m->second->m->fieldName , field ,  
  22.                                                          lexNumCmp );  
  23.         switch ( cmp ) {  
  24.         case LEFT_SUBFIELD: { // Mod is embedded under this element  
  25.             uassert( 10145,//如这种情况m->fieldName=a.b.c,field=a.b  
  26.                      str::stream() << "LEFT_SUBFIELD only supports Object: " << field  
  27.                      << " not: " << e.type() , e.type() == Object || e.type() == Array );  
  28.             if ( onedownseen.count( e.fieldName() ) == 0 ) {  
  29.                 onedownseen.insert( e.fieldName() );  
  30.                 if ( e.type() == Object ) {//深入到下一层创建更深层的对象  
  31.                     BSONObjBuilder bb( builder.subobjStart( e.fieldName() ) );  
  32.                     stringstream nr; nr << root << e.fieldName() << ".";  
  33.                     createNewObjFromMods( nr.str() , bb , e.Obj() );  
  34.                     bb.done();  
  35.                 }  
  36.                 else {  
  37.                     BSONArrayBuilder ba( builder.subarrayStart( e.fieldName() ) );  
  38.                     stringstream nr; nr << root << e.fieldName() << ".";  
  39.                     createNewArrayFromMods( nr.str() , ba , BSONArray( e.embeddedObject() ) );  
  40.                     ba.done();  
  41.                 }  
  42.                 // inc both as we handled both  
  43.                 e = es.next();  
  44.                 m++;  
  45.             }  
  46.             else {  
  47.                 massert( 16069 , "ModSet::createNewFromMods - "  
  48.                         "SERVER-4777 unhandled duplicate field" , 0 );  
  49.             }  
  50.             continue;  
  51.         }  
  52.         case LEFT_BEFORE: // Mod on a field that doesn't exist  
  53.             _appendNewFromMods( root , *m->second , builder , onedownseen );  
  54.             m++;  
  55.             continue;  
  56.         case SAME://要更新的域和原本的域是一样的,则直接应用更新,这里添加了更新后的数据  
  57.             m->second->apply( builder , e );  
  58.             e = es.next();  
  59.             m++;  
  60.             continue;  
  61.         case RIGHT_BEFORE: // field that doesn't have a MOD  
  62.             builder.append( e ); // if array, ignore field name  
  63.             e = es.next();  
  64.             continue;  
  65.         case RIGHT_SUBFIELD://比如说e现在是a.b.c,但是m是a,这种情况是不能出现的  
  66.             massert( 10399 ,  "ModSet::createNewFromMods - RIGHT_SUBFIELD should be impossible" , 0 );  
  67.             break;  
  68.         default:  
  69.             massert( 10400 ,  "unhandled case" , 0 );  
  70.         }  
  71.     }  
  72.     // finished looping the mods, just adding the rest of the elements  
  73.     while ( !e.eoo() ) {  
  74.         builder.append( e );  // if array, ignore field name  
  75.         e = es.next();  
  76.     }  
  77.     // do mods that don't have fields already  
  78.     for ( ; m != mend; m++ ) {//最后添加要更新的域的数据  
  79.         _appendNewFromMods( root , *m->second , builder , onedownseen );  
  80.     }  
  81. }  
        这个函数思想很简单就是根据要更新的值和原本的值创建一条新的doc,但是因为各种回调函数,

以及比较操作所以需要多多调试才能够体会.最后来看看updateRecord函数.

[cpp]  view plain copy
  1. const DiskLoc DataFileMgr::updateRecord(  
  2.     const char *ns,  
  3.     NamespaceDetails *d,  
  4.     NamespaceDetailsTransient *nsdt,  
  5.     Record *toupdate, const DiskLoc& dl,  
  6.     const char *_buf, int _len, OpDebug& debug,  bool god) {  
  7.     BSONObj objOld = BSONObj::make(toupdate);  
  8.     BSONObj objNew(_buf);  
  9.     if( !objNew.hasElement("_id") && objOld.hasElement("_id") ) {//添加一个_id  
  10.         /* add back the old _id value if the update removes it.  Note this implementation is slow 
  11.            (copies entire object multiple times), but this shouldn't happen often, so going for simple 
  12.            code, not speed. 
  13.         */  
  14.         BSONObjBuilder b;  
  15.         BSONElement e;  
  16.         verify( objOld.getObjectID(e) );  
  17.         b.append(e); // put _id first, for best performance  
  18.         b.appendElements(objNew);  
  19.         objNew = b.obj();  
  20.     }  
  21.     /* duplicate key check. we descend the btree twice - once for this check, and once for the actual inserts, further 
  22.        below.  that is suboptimal, but it's pretty complicated to do it the other way without rollbacks... 
  23.     */  
  24.     vector<IndexChanges> changes;  
  25.     bool changedId = false;//遍历index得到所有的index变化  
  26.     getIndexChanges(changes, ns, *d, objNew, objOld, changedId);  
  27.     dupCheck(changes, *d, dl);  
  28.     if ( toupdate->netLength() < objNew.objsize() ) {//数据长度不够,删除其,然后再插入,这里的数据长度包括了old record  
  29.                                          //本来的数据长度以及后面留下的padding  
  30.         // doesn't fit.  reallocate -----------------------------------------------------  
  31.         uassert( 10003 , "failing update: objects in a capped ns cannot grow", !(d && d->isCapped()));  
  32.         d->paddingTooSmall();//数据长度不够后调整paddingFit,让下次分配更改的内存避免修改时长度再次不够  
  33.         deleteRecord(ns, toupdate, dl);  
  34.         DiskLoc res = insert(ns, objNew.objdata(), objNew.objsize(), god);  
  35.         if (debug.nmoved == -1) // default of -1 rather than 0  
  36.             debug.nmoved = 1;  
  37.         else  
  38.             debug.nmoved += 1;  
  39.         return res;  
  40.     }  
  41.     nsdt->notifyOfWriteOp();  
  42.     d->paddingFits();  
  43.     /* have any index keys changed? */  
  44.     {  
  45.         int keyUpdates = 0;//下面数据长度够,所以先删除过时的index和添加新的index  
  46.         int z = d->nIndexesBeingBuilt();//最后复制数据  
  47.         for ( int x = 0; x < z; x++ ) {  
  48.             IndexDetails& idx = d->idx(x);  
  49.             IndexInterface& ii = idx.idxInterface();  
  50.             for ( unsigned i = 0; i < changes[x].removed.size(); i++ ) {  
  51.                     bool found = ii.unindex(idx.head, idx, *changes[x].removed[i], dl);  
  52.                     if ( ! found ) {  
  53.                         RARELY warning() << "ns: " << ns << " couldn't unindex key: " << *changes[x].removed[i]   
  54.                                          << " for doc: " << objOld["_id"] << endl;  
  55.                     }  
  56.             }  
  57.             BSONObj idxKey = idx.info.obj().getObjectField("key");  
  58.             Ordering ordering = Ordering::make(idxKey);  
  59.             keyUpdates += changes[x].added.size();  
  60.             for ( unsigned i = 0; i < changes[x].added.size(); i++ ) {  
  61.                     /* we did the dupCheck() above.  so we don't have to worry about it here. */  
  62.                     ii.bt_insert(  
  63.                         idx.head,  
  64.                         dl, *changes[x].added[i], ordering, /*dupsAllowed*/true, idx);  
  65.                 }  
  66.         }  
  67.         debug.keyUpdates = keyUpdates;  
  68.     }  
  69.     //  update in place  
  70.     int sz = objNew.objsize();//实际对象的数据复制  
  71.     memcpy(getDur().writingPtr(toupdate->data(), sz), objNew.objdata(), sz);  
  72.     return dl;  
  73. }  

        从update的流程来看整个过程不复杂,但是其中细节很多,需要多多调试才能够明白,其中貌似有个bug

代码中以说明.需要记住的是如果更新后数据的长度超过了原doc能够存储的数据长度,那么更新变更为一次

数据的删除以及一次数据的插入操作.


本文链接: mongodb源码分析(十二)数据的更新

作者: yhjj0108,杨浩


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值