- 전체
- Sample DB
- database modeling
- [표준 SQL] Standard SQL
- G-SQL
- 10-Min
- ORACLE
- MS SQLserver
- MySQL
- SQLite
- postgreSQL
- 데이터아키텍처전문가 - 국가공인자격
- 데이터 분석 전문가 [ADP]
- [국가공인] SQL 개발자/전문가
- NoSQL
- hadoop
- hadoop eco system
- big data (빅데이터)
- stat(통계) R 언어
- XML DB & XQuery
- spark
- DataBase Tool
- 데이터분석 & 데이터사이언스
- Engineer Quality Management
- [기계학습] machine learning
- 데이터 수집 및 전처리
- 국가기술자격 빅데이터분석기사
- 암호화폐 (비트코인, cryptocurrency, bitcoin)
NoSQL [mongodb] How to Update a Document in MongoDB using Java
2020.12.14 15:28
[mongodb] How to Update a Document in MongoDB using Java
Introduction
Updating documents is a common task in database management. You might want to update a single document, or you may need to update a number of documents that meet some specified query criteria. Regardless of the exact requirements, it’s easy to update MongoDB documents with some simple Java code. In this article, we’ll provide instructions for updating a MongoDB document using Java.
Prerequisites
Before we move on to our code examples, it’s important to review the prerequisites for this task and make sure everything is in place. There are only a few system requirements:
-
You’ll need to make sure that MongoDB is installed and properly configured, as well as the MongoDB driver for Java.
-
You’ll also need to check that the latest Java JDK is installed and configured before proceeding.
-
Last but not least, you’ll need to check that the MongoDB service is running.
NOTE: Throughout this article, we’ll assume that the MongoDB version being used is 4.0 and the MongoDB Java Driver is 3.8.2.
The MongoDB Test Data
You don’t want to accidentally update any production data when you follow along with the examples in this tutorial, so it’s best to create a small sample dataset instead. You’ll need to insert the following documents to your chosen collection name. In this example, our sample collection will be called “webHostInfo”:
| ID | Number | Hosting Name | Location |
|---|---|---|---|
| 5ce5424e5623d0458e941e48 | 1 | GoDaddy | USA |
| 5ce5424e5623d0458e941e49 | 2 | Blue Host | USA |
| 5ce5424e5623d0458e941e4a | 3 | Just Host | USA |
| 5ce5424e5623d0458e941e4b | 4 | Rose Hosting | USA |
| 5ce5424e5623d0458e941e4c | 5 | WebDotcom | USA |
- The MongoDB Version:
The MongoDB Connection Details
Now that we’ve checked for all our system requirements and created a small set of sample data, we can focus on the Java code. The first code segment we’ll need is shown below:
In the code displayed above, we establish a connection to our MongoDB deployment. We then access the database (webHost) as well as the specified collection (webHostInfo).
Updating a MongoDB Document using findOne() Method
The following examples will show different ways to update a single MongoDB document using the findOne() method in a Java application.
Update a MongoDB Document using the “$set” operator in Java
The code shown below will update the value of the field hostingName from “GoDaddy” to “goDaddy”.
Let’s take a closer look at what’s going on in this code. The following new BasicDBObject objects have been created, and they all have different purposes:
-
query— holds the field name and current value of that field for the document to be updated -
newDocument— holds the new value of the fieldhostingNamefor the document we’re updating -
updateObject— we pass in the$setoperator to update the specified field.
Finally, the updateOne() method performs the update operation, passing in the query and updateObject objects.
If you’d like to verify that the operation was a success, use the following command in the MongoDB shell:
You should get results that look something like this:
You can see that the value of "hostingName" has changed to "goDaddy", confirming that our delete operation was a success.
Update a MongoDB Documents using “$inc” operator in Java
Our next example will show how to use the $inc modifier to increase a particular value:
In the code shown above, we find a MongoDB document within the webHostInfo collection that matches the specified criteria, and it will increase that document’s number field by 6.
Updating a MongoDB Documents using findMany() Method
So far, we’ve looked at examples where a single MongoDB document is updated. The next examples will show different ways to update multiple MongoDB documents at a time using the findMany() method in a Java application.
Update a MongoDB Documents using “$set” operator in Java.
The following code will update all MongoDB documents that match the specified criteria. In this case, the criteria is that the "location" field must have the value "USA". We’ll be updating these matching documents by setting the value of their "number" field to 888:
The results that are returned should look something like this:
Conclusion
If you’re working with MongoDB, you’ll find that you’ll need to update documents from time to time. Whether you need to update a single document or all documents that match a certain set of criteria, the task can be easily accomplished in Java. With the detailed examples provided in this article, you’ll have no trouble updating a MongoDB document using Java.
[출처] https://kb.objectrocket.com/mongo-db/how-to-update-a-document-in-mongodb-using-java-384
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
댓글 0
| 번호 | 제목 | 글쓴이 | 날짜 | 조회 수 |
|---|---|---|---|---|
| 공지 | 오라클 기본 샘플 데이터베이스 | 졸리운_곰 | 2014.01.02 | 86824 |
| 공지 | [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE | 가을의 곰을... | 2013.02.10 | 79118 |
| 공지 | [G_SQL] Sample Database | 가을의 곰을... | 2012.05.20 | 95875 |
| 5 | XML database | 졸리운_곰 | 2016.11.29 | 4393 |
| 4 |
Learn XQuery in 10 Minutes: An XQuery Tutorial
| 졸리운_곰 | 2016.11.29 | 2001 |
| 3 |
xquery-tutorial.pdf
| 졸리운_곰 | 2016.11.29 | 1729 |
| 2 | XML 문서 가져오기 및 XQuery 쿼리 예제 | 졸리운_곰 | 2016.11.29 | 1564 |
| 1 |
[SQL] XQuery로 XML Data에 접근하기
| 졸리운_곰 | 2016.11.29 | 1926 |

