Du kan använda Array.map för att forma varje indata för användning med en bulkskrivning.
Beteendet du beskriver verkar använda email för att identifiera varje dokument.
Du angav inte vad som skulle hända med andra fält i dokumenten. Om du vill lämna andra fält ifred, använd $set för att ta bort fält som inte nämns i inkommande data, använd $replace .
I skalet ser det ut så här:
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" }
Ta en titt på Model.bulkWrite() för ett exempel på hur man gör detta i mongoose.