2016-08-07 19 views
0

我讀過文學的各個位,而我看到,在mongoskin和批量操作? (MongoDB的3.2,mongoskin 2.1.0和2.2.0)

https://stackoverflow.com/a/25636911

提問者是看到了同樣的問題。

我的代碼如下所示:

coll = db.collection('foobar'); 
bulk = coll.initializeUnorderedBulkOp(); 

for entry in messages { 
    bulk.insert(entry); 
} 

bulk.execute(function (err, result) { 
    if (err) throw err 
    inserted += result.nInserted 
}); 

大部分是對象

bulk.insert工作得很好

bulk.execute未定義

在計算器問題的答案說:「只有db.collection()的回調風格起作用,所以我試過了:

db.collection('foobar', function (err, coll) { 
    logger.debug "got here" 
    if (err) throw err 
    bulk = coll.initializeUnorderedBulkOp() 
    ... same code as before 

我們從來沒有去過「暗示」,意味着db.collection()的「回調風味」在3.0下降了嗎?

不幸的是,我的python比我的JS原型製作技巧要好,所以查看皮膚源代碼對我來說沒有任何意義。

用mongoskin 2.1.0和2.2.0 mongodb JS驅動程序進行批量操作的方法是什麼,或者這一切都沒有實現?

回答

0

至少有兩個答案:

(1)使用INSERT,但數組形式,所以你插入多個文檔,一次通話。奇蹟般有效。 (2)如果您真的需要批量操作,您需要從mongoskin切換到本地mongo界面,但僅限於那一個調用。 這有點兒吮吸,因爲它是用在mongoskin一個專用接口,但它也堅持mongoskin最有效的方法:

(例如,在CoffeeScript中)

// bulk write all the messages in "messages" to a collection 
// and insert the server's current time in the recorded field of 
// each message 

// use the _native interface and wait for callback to get collection 
db._native.collection collectionName, (err, collection) -> 
    bulk = collection.initializeUnorderedBulkOp() 
    for message in messages 
     bulk.find 
      _id: message._id 
     .upsert().updateOne 
      $set: message 
      $currentDate: 
       recorded: true 
    bulk.execute (err, result) -> 
     // ... error and result checking code 

或(3)如果你想實現即$的currentdate並沒有任何通用的批量操作,請參考解決方案(1),但使用不是非常充分證明BSON對象時間戳()不帶參數:

for msg in messages: 
    msg.recorded = Timestamp() 
db.mycollection.insert(msg) 

將做批量插入和設置時間戳記到數據庫服務器的時間在記錄寫入數據庫時​​。