MongoDB 更新集合文档

huangapple go评论73阅读模式
英文:

mongoDB update collection documents

问题

我有一个更新请求,该请求应该更新我的数据库中的现有数据,就像以下示例一样:

现有数据 => [{_id:"abnc214124",name:"mustafa",age:12,etc...}, {_id:"abnc21412432",name:"mustafa1",age:32,etc...}, {_id:"abnc214124123",name:"mustafa3",age:52,etc...} etc... ]

新数据 => [{_id:"abnc214124",name:"mustafaxxx",age:12,etc...}, {_id:"abnc21412432",name:"mustafa1",age:35,etc...}, {_id:"abnc214124123",name:"mustafa3",age:20,etc...} etc... ]
要更新的字段:
在第一个文档中,更新名称。
在第二个文档中,更新年龄。
在第三个文档中,更新年龄。
最佳的方法是如何更新现有数据,而不影响旧字段(未修改字段)?
顺便说一下,

我尝试循环遍历文档并检查字段然后更新它们,但这会导致长时间的响应时间,为了解决这个问题,我在NodeJS上使用了多线程,现在我需要更好的解决方案。

英文:

I have an update request and that request should update the existing data in my database like the flowing example

existing data => [{_id:"abnc214124",name:"mustafa",age:12,etc...},
{_id:"abnc21412432",name:"mustafa1",age:32,etc...},
{_id:"abnc214124123",name:"mustafa3",age:52,etc...}
etc...
]

new Data => [{_id:"abnc214124",name:"mustafaxxx",age:12,etc...},
{_id:"abnc21412432",name:"mustafa1",age:35,etc...},
{_id:"abnc214124123",name:"mustafa3",age:20,etc...}
etc...
]

the updated fields :
in the first document name
second age
third age
what is the best way to update the existing data without affect the old fields (not modified fields)
BTW

I tried to loop through documents and check the fields then update them but this will cause long response time and to solve this I used multithread on NodeJS and now I need better solution

答案1

得分: 1

要更新集合中的多个文档,您可以使用 updateMany()

这是 updateMany() 的示例

db.collection.updateMany(
   <filter>,
   <update>,
   {
      multi: true
   }
)

在上面的示例中:

filter 参数指定要更新的文档

update 参数指定要执行的更新

英文:

To Update the multiple documents of a collection. you can use updateMany()

This is the example of updateMany()

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

db.collection.updateMany(
   &lt;filter&gt;,
   &lt;update&gt;,
   {
      multi: true
   }
)

<!-- end snippet -->

In Above example:

filter parameter specifies which documents to update

update parameter specifies the update to be performed

huangapple
  • 本文由 发表于 2023年1月8日 16:20:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75046365.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定