mongoskin 和批量操作? (mongodb 3.2,猫皮 2.1.0 和 2.2.0)

mongoskin and bulk operations? (mongodb 3.2, mongoskin 2.1.0 & 2.2.0)

我阅读了各种文学作品,我看到了与

中的提问者相同的问题

在看。

我的代码如下所示:

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 未定义

Whosebug 问题中的答案说,“只有 db.collection() 的回调风格有效,所以我尝试了:

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

我们从来没有达到 "got here" 暗示 db.collection() 的 "callback flavor" 在 3.0 中被删除了?

不幸的是,我的 python 比我的 JS 原型制作技术要好得多,所以看皮肤源代码对我来说没有任何意义。

使用 mongoskin 2.1.0 和 2.2.0 mongodb JS 驱动程序进行批量操作的正确方法是什么,还是根本没有实现?

至少有两个答案:

(1) 使用insert,但是数组形式,一次插入多个文档。就像一个魅力。

(2) 如果您确实需要批量操作,则需要从 mongo 皮肤切换到本机 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 对象 Timestamp() 不带参数:

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

这将执行批量插入并将时间戳设置为记录写入数据库时​​数据库服务器的时间。