update document in mongodb using java -摘自网络

update document in mongodb using java:

Mongodb driver provides functionality to update document in mongodb using java. Update is a process in which single or multiple documents can be updated based on certain criteria. Let us see what javadoc says about update

 

 

Update a single document in the collection according to the specified arguments.
Parameters:
filter – a document describing the query filter, which may not be null.
update – a document describing the update, which may not be null. The update to apply must include only update operators.
Returns:
the result of the update one operation

Let us try to understand with an example. To update document in mongodb using java, consider we have below document in collection.

Now we want to update the salary to 80000. We have to provide

  • A document which will identify above document. Let us say we want to update salary where name is “Harish Taware”
  • A document which will specify the “$set” operation and the value which will itself be a Document.

Consider below code

Here,

  • filter variable stores the document with name Harish Taware
  • newValue is the document which specifies salary needs to be updated to 90000
  • updateOperationDocument specifies that a set operation is to be performed.
  • collection.updateOne(filter,updateOperationDocument)  actually does the job of updating document.

Here is complete code

Run the program to update mongodb document using java. Notice the salary is changed

Just like updateOne, we have updateMany() method to update multiple documents at once. I hope the article helped understand how to update document in mongodb using java.

posted @   iDEAAM  阅读(510)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
点击右上角即可分享
微信分享提示