更新多条记录并插入(如果不存在)

编程入门 行业动态 更新时间:2024-10-22 09:40:18
本文介绍了更新多条记录并插入(如果不存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可以说我的测试数据是

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.

更多推荐

更新多条记录并插入(如果不存在)

本文发布于:2023-10-25 08:48:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1526478.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不存在   多条

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!