我已经阅读了各种文献,我看到的问题和提问者在
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未定义
堆栈溢出问题中的答案是:“只有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驱动程序进行批量操作的正确方式是什么,还是根本不再实现?
发布于 2016-09-03 17:12:19
至少有两个答案:
(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)它将执行批量插入,并将时间戳设置为记录写入数据库时数据库服务器的时间。
https://stackoverflow.com/questions/38810387
复制相似问题