bulkWrite和initialize(Un)orderedBulkOp是MongoDB提供的两种执行批量写操作的方法。它们的主要区别在于执行顺序和错误处理。
示例代码:
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017', function(err, client) {
if (err) throw err;
const db = client.db('mydb');
const collection = db.collection('mycollection');
const operations = [
{ insertOne: { document: { name: 'John' } } },
{ updateOne: { filter: { name: 'John' }, update: { $set: { age: 30 } } } },
{ deleteOne: { filter: { name: 'John' } } }
];
collection.bulkWrite(operations, function(err, result) {
if (err) throw err;
console.log(result);
client.close();
});
});
示例代码:
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017', function(err, client) {
if (err) throw err;
const db = client.db('mydb');
const collection = db.collection('mycollection');
const bulk = collection.initializeUnorderedBulkOp();
bulk.insert({ name: 'John' });
bulk.find({ name: 'John' }).updateOne({ $set: { age: 30 } });
bulk.find({ name: 'John' }).deleteOne();
bulk.execute(function(err, result) {
if (err) throw err;
console.log(result);
client.close();
});
});
在上述代码中,initializeUnorderedBulkOp方法创建了一个无序的Bulk对象,然后可以通过insert、update和delete等方法添加操作。最后,使用execute方法执行操作。
总结: