问题
Lets say my test data is
db.multiArr.insert({"ID" : "fruit1","Keys" : "apple"})
db.multiArr.insert({"ID" : "fruit2","Keys" : "carrot"})
db.multiArr.find({'ID': {$in: ['fruit1', 'fruit2']}})
if i want to update or insert a ID i can do it using
db.multiArr.update(
{'ID': "fruit12"},
{
'ID': "fruit12"
"$push": {
"Keys": "tomato"
}
},
upsert=True
)
i want to update or insert multiple records, i know the below query inserts only 1 row
db.multiArr.update(
{"ID": {"$in: ["fruit123", "fruit1234"]}},
{"ID": "---", "Keys": "tomato"},
upsert=true
)
is there a way to update/insert multiple records?
回答1:
Your thinking on this is the wrong way around. Instead you take the "array" and turn that into operations. Instead of sending multiple "requests" you send multiple "operations" in "one request". With Bulk Operations using .bulkWrite()
var newKeys = ["fruit123", "fruit1234" ];
db.multiArr.bulkWrite(
newkeys.map( key => {
return {
"updateOne": {
"filter": { "ID": key },
"update": { "$set": { "Keys": "tomato" } },
"upsert": true
}
}
})
)
Here using a regular JavaScript .map() to transform the array content of newKeys
into an array of "bulk write operations" statements to send to the server. In other languages the basic concept remains the same.
Over the wire, the send and response with the server is done in "one request", whilst the "package" sent for execution contains multiple actions.
If needed the return of this method in all API's is a BulkWriteResult which contains details of matched documents, updates and upserts as appropriate.
来源:https://stackoverflow.com/questions/44236312/update-multi-records-and-insert-if-not-present