Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Thực hiện Bulk Insert (chèn hàng loạt) trong MongoDB

Để chèn hàng loạt tài liệu hiệu quả, sử dụng initializeUnorderedBulkOp() (bulk operations không thứ tự). Tạo bulk operation:

> var bulkInsertDoc = db.demo663.initializeUnorderedBulkOp();
> bulkInsertDoc.insert( { Name: "John", CountryName: "US" } );
> bulkInsertDoc.insert( { Name: "Chris", CountryName: "UK" } );
> bulkInsertDoc.insert( { Name: "David", CountryName: "AUS" } );
> bulkInsertDoc.execute();
BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 3, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })

Hiển thị dữ liệu đã insert:

> db.demo663.find();

Kết quả 3 tài liệu:

Bulk Operations loại:

  • initializeUnorderedBulkOp() - thực hiện song song, không đảm bảo thứ tự, dừng khi lỗi (tiếp tục các op khác)
  • initializeOrderedBulkOp() - thực hiện tuần tự, dừng hẳn khi gặp lỗi

Hỗ trợ operations: insert(), update(), updateOne(), replaceOne(), remove(), removeOne().

API mới (MongoDB 3.2+): Dùng bulkWrite() thay thế:

db.demo663.bulkWrite([
  { insertOne: { document: { Name: "John", CountryName: "US" } } },
  { insertOne: { document: { Name: "Chris", CountryName: "UK" } } },
  { insertOne: { document: { Name: "David", CountryName: "AUS" } } }
])

Lợi ích: Giảm network round-trips, tối ưu write throughput, atomic per operation.