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

时间:2016-08-07 02:39:08

标签: mongoskin

我已经阅读过各种各样的文献,而且我看到了提问者的相同问题

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

stackoverflow问题中的答案说,“只有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驱动程序进行批量操作的正确方法是什么,或者这是不是已经完全实现了?

1 个答案:

答案 0 :(得分:0)

至少有两个答案:

(1)使用insert,但是使用数组形式,因此您可以通过一次调用插入多个文档。像魅力一样。

(2)如果你真的需要批量操作,你需要从mongoskin切换到本机mongo接口,但只需要进行一次调用。 这有点糟糕,因为它在mongoskin中使用私人界面,但它也是坚持使用mongoskin的最有效方式:

(coffeescript中的例子)

user.todo_lists.map { |todo_list| todo_list.todo_items.completed }.flatten

或(3)如果你想实现$ currentDate而不是任何泛型批量操作,请参考解决方案(1),但使用没有很好记录的BSON对象Timestamp(),不带参数:

// 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

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

相关问题