Bạn có thể sử dụng Array.map để định hình từng đầu vào để sử dụng với việc ghi hàng loạt.
Hành vi bạn đang mô tả dường như đang sử dụng email trường để xác định từng tài liệu.
Bạn đã không chỉ ra điều gì sẽ xảy ra với các trường khác trong tài liệu. Nếu bạn muốn để nguyên các trường khác, hãy sử dụng $set để xóa bất kỳ trường nào không được đề cập trong dữ liệu đến, hãy sử dụng $replace .
Trong shell, nó trông giống như:
PRIMARY> db.users.find()
{ "_id" : 1, "email" : "example@sqldat.com", "name" : "one" }
{ "_id" : 2, "email" : "example@sqldat.com", "name" : "two" }
{ "_id" : 3, "email" : "example@sqldat.com", "name" : "three" }
PRIMARY> let users = [
{ email: "example@sqldat.com", name: "oneeee" },
{ email: "example@sqldat.com", name: "twoooo" },
{ email: "example@sqldat.com", name: "three" },
{ email: "example@sqldat.com", name: "four" }
]
PRIMARY> let bulkUpdate = db.users.initializeUnorderedBulkOp()
PRIMARY> users.forEach(u => bulkUpdate.find({email:u.email}).upsert().update({$set:u}))
PRIMARY> bulkUpdate.execute()
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 0,
"nUpserted" : 1,
"nMatched" : 3,
"nModified" : 2,
"nRemoved" : 0,
"upserted" : [
{
"index" : 3,
"_id" : ObjectId("5f5e79ff28ee536df4c4a88e")
}
]
})
PRIMARY> db.users.find()
{ "_id" : 1, "email" : "example@sqldat.com", "name" : "oneeee" }
{ "_id" : 2, "email" : "example@sqldat.com", "name" : "twoooo" }
{ "_id" : 3, "email" : "example@sqldat.com", "name" : "three" }
{ "_id" : ObjectId("5f5e79ff28ee536df4c4a88e"), "email" : "example@sqldat.com", "name" : "four" }
Hãy xem Model.bulkWrite () để biết ví dụ về cách thực hiện điều này trong mongoose.