[英]MongoDB: atomic call on 2 collections (find + insert)
如何自動獲取最新的“回合”記錄ObjectId並在插入“存款”集合時使用該記錄?
這個帖子的答案說這是不可能完成的: 在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');
});
});
在Mongodb中插入文檔具有可以使用的回調函數。 該回調函數具有第二個參數,該參數返回插入的文檔。
我嘗試使用console.log打印第二個參數。 看起來像 :
{ result: { ok: 1, n: 1 },
ops:
[ { username: 'user1',
password: 'password1',
_id: 562099bae1872f58b3a22aed } ],
insertedCount: 1,
insertedIds: [ 562099bae1872f58b3a22aed ]
}
insertedIds
是保存插入的一個或多個文檔的_id的數組。
因此,您可以在插入第一個集合的函數回調中將對象插入第二個集合。 有點混亂。
簡單來說:將文檔插入第一個集合。 在回調中,將文檔插入第二個集合中。
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');
}
});
});
}
});
}
});
似乎無法對MongoDB中的2個集合進行原子操作,如以下答案所示:
我將問題擱置一旁,因為它的重點稍有不同(不是2個更新,而是find + insert)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.