【问题标题】:mongoskin and bulk operations? (mongodb 3.2, mongoskin 2.1.0 & 2.2.0)mongoskin 和批量操作? (mongodb 3.2, mongoskin 2.1.0 & 2.2.0)
【发布时间】:2016-10-16 01:23:52
【问题描述】:

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

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 是一个对象

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 驱动程序进行批量操作的正确方法是什么,或者根本不再实现?

【问题讨论】:

    标签: mongoskin


    【解决方案1】:

    至少有两个答案:

    (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 对象 Timestamp():

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

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

    【讨论】:

      猜你喜欢
      • 2014-07-05
      • 2014-07-26
      • 2014-03-19
      • 2015-12-09
      • 2012-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多