2015-10-15 59 views
1

如何以原子方式獲取最新的「rounds」記錄ObjectId並在插入到「存款」集合時使用它?MongoDB:對2個集合進行原子調用(查找+插入)

這個帖子回答說不能這樣做:Is there any way to atomically update two collections in MongoDB? 這是真的嗎?

在過程A中,我想自動查找最新的圓形標識符(rid)並將其插入到存款中。競爭條件是,在A發現擺脫之後,另一個進程B可能會插入回合,所以現在A有一個不是最新的擺脫,但是落後1。 A怎樣才能找到擺脫的方式+將這個擺脫到存款(對這兩個集合採取行動)原子上?

// GET ROUND ID (RID) OF LATEST 

    var rid; 
    db.rounds.find().limit(1).sort({$natural:-1}, function(err, latestInsertedRound){ 
     rid = latestInsertedRound[0]._id; 
     print(rid, 'rid'); // if another process B inserts now, this rid is 1 behind 

     // INSERT INTO DEPOSITS 

     db.deposits.insert({uid:uid, iid:iid, rid:rid}, function(err, insertedDeposit){ 
      print(insertedDeposit, 'insertedDeposit'); 
     }); 
    }); 
+0

爲什麼你需要'最新'的ID如果你仍然有連接到保存的存款? –

+0

因爲一輪結束後,存款應該進入最新一輪。無論如何,這將如何完成? – mylord

回答

1

在Mongodb中插入文檔有一個可以使用的回調函數。這個回調函數有第二個參數返回插入的文檔。

我試着用console.log打印第二個參數。它看起來像:

{ result: { ok: 1, n: 1 }, 
ops: 
    [ { username: 'user1', 
     password: 'password1', 
     _id: 562099bae1872f58b3a22aed } ], 
    insertedCount: 1, 
    insertedIds: [ 562099bae1872f58b3a22aed ] 
} 

insertedIds是存放插入的文檔或文檔的_ids的數組。

因此,您可以在插入第一個集合的函數回調的第二個集合中插入您的對象。有點混亂。

簡而言之:將文檔插入到第一個集合中。在回調中,將文檔插入到第二個集合中。

MongoClient.connect(MONGOLAB_URI, function (err, db) { 
    if (err) 
     console.log("We have some error : " + err); 

    else {    
     db.createCollection('rounds', function (err, rounds) { 
      if (err) { 
       console.log('Error while creating rounds collection'); 
       throw err; 
      } 

      else { 
       rounds.insert({ 'username' : 'user1', 'password' : 'password1' }, function(err,docsInserted){ 
        console.log('Last document inserted id :', docsInserted.insertedIds[0]); 

        //inserting the document in the function callback 
        db.createCollection('deposits', function (err, deposits) { 
         if (err) { 
          console.log('Error while creating deposits collection'); 
          throw err; 
         } 

         else { 
          //change array index according to your need 
          //you may be inserting multiple objects simultaneously 
          deposits.insert({'last_inserted_object' : docsInserted.insertedIds[0]); 

          console.log('inserted into deposits collection'); 
         } 
        }); 
       }); 
      } 
     }); 
    } 
}); 
+0

不錯!整個事物是否是原子的?插入存款時最新一輪的原子發現如何?這其實就是我需要的原子。 – mylord

+0

@ mylord由於沒有事務,現在可以有原子操作來修改多個文檔。 –

+0

@ mylord是否使用了兩個不同的調用,一個用於插入回合集合,另一個用於插入存款集合...? –