这是一个安全的方式插入和更新mongodb中的对象数组?

以下代码更新指定对象的数组,或者在对象不在数据库中时插入。 它工作正常,但我是新的MongoDB,我不知道这是一个安全或快速的方式来做到这一点。

也许我应该使用updateMany ? 我试图使用它,但我无法获得与下面的代码相同的行为。

mongodb.connect(mongo_url, function(err, db) { if(err) console.log(err) else { var mongo_products_collection = db.collection("products") mongoUpsert(mongo_products_collection, data_products, function() { db.close() }) } }) function mongoUpsert(collection, data_array, cb) { var data_length = data_array.length for (var i=0; i < data_length; i++) { collection.update( {product_id: data_array[i].product_id}, data_array[i], {upsert: true} ) } return cb(false) } 

使用bulkWrite API执行更新可以更好地处理这个问题

 mongodb.connect(mongo_url, function(err, db) { if(err) console.log(err) else { var mongo_products_collection = db.collection("products") mongoUpsert(mongo_products_collection, data_products, function() { db.close() }) } }) function mongoUpsert(collection, data_array, cb) { var bulkUpdateOps = data_array.map(function(data) { return { "updateOne": { "filter": { "product_id": data.product_id, "post_modified": { "$ne": data.post_modified } }, "update": { "$set": data }, "upsert": true } }; }); collection.bulkWrite(bulkUpdateOps, function(err, r) { // do something with result }); return cb(false); } 

如果你正在处理更大的数组,例如> 1000,那么可以考虑将批量写入500的服务器,因为你没有向服务器发送每个请求,所以每500个请求中只有一次请求,这样可以提供更好的性能。

对于批量操作,MongoDB每个批次的默认内部限制是1000次操作,因此从500个文档中select500个文档是有好处的,因为您可以控制批量大小,而不是让MongoDB强制实施默认操作, > 1000文件。 所以对于第一种方法中的上述情况,可以一次写入所有数组,因为这是小的,但是500select是针对较大的数组。

 var ops = [], counter = 0; data_array.forEach(function(data) { ops.push({ "updateOne": { "filter": { "product_id": data.product_id, "post_modified": { "$ne": data.post_modified } }, "update": { "$set": data }, "upsert": true } }); counter++; if (counter % 500 == 0) { collection.bulkWrite(ops, function(err, r) { // do something with result }); ops = []; } }) if (counter % 500 != 0) { collection.bulkWrite(ops, function(err, r) { // do something with result } }