问题描述
可以说我的测试数据是
db.multiArr.insert({"ID" : "fruit1","Keys" : "apple"})
db.multiArr.insert({"ID" : "fruit2","Keys" : "carrot"})
db.multiArr.find({'ID': {$in: ['fruit1', 'fruit2']}})
如果我想更新或插入一个ID,我可以使用
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
)
我想更新或插入多条记录,我知道以下查询仅插入1行
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?
推荐答案
您对此的思考是错误的方法.取而代之的是,您采用数组"并将其转化为运算.而不是发送多个请求",而是在一个请求"中发送多个操作".使用 .bulkWrite()
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
}
}
})
)
这里使用常规JavaScript .map()
将newKeys
的数组内容转换为批量写入操作"语句的数组,以发送到服务器.在其他语言中,基本概念保持不变.
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.
如果需要,则在所有API中返回的方法是 BulkWriteResult
,其中包含匹配文档的详细信息,更新和适当的upserts.
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.
这篇关于更新多条记录并插入(如果不存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!