[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:
1
2
3
4
5
{ "_id" : ObjectId("5ce5424e5623d0458e941e48"), "hostingName" : "GoDaddy", "number" : 1, "location" : "USA" }
{ "_id" : ObjectId("5ce5424e5623d0458e941e49"), "hostingName" : "Blue Host", "number" : 2, "location" : "USA" }
{ "_id" : ObjectId("5ce5424e5623d0458e941e4a"), "hostingName" : "Just Host", "number" : 3, "location" : "USA" }
{ "_id" : ObjectId("5ce5424e5623d0458e941e4b"), "hostingName" : "Rose Hosting", "number" : 4, "location" : "USA" }
{ "_id" : ObjectId("5ce5424e5623d0458e941e4c"), "hostingName" : "webDotcom", "number" : 5, "location" : "USA" }

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:

1
2
3
MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017");
MongoDatabase db = mongo.getDatabase("webHost");
MongoCollection<document> webHostColl = db.getCollection("webHostInfo");

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”.

1
2
3
4
5
6
7
8
9
10
BasicDBObject query = new BasicDBObject();
query.put("hostingName""GoDaddy"); // (1)

BasicDBObject newDocument = new BasicDBObject();
newDocument.put("hostingName""goDaddy"); // (2)

BasicDBObject updateObject = new BasicDBObject();
updateObject.put("$set", newDocument); // (3)

db.getCollection("webHostInfo").updateOne(query, updateObject); // (4)

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:

  1. query — holds the field name and current value of that field for the document to be updated

  2. newDocument — holds the new value of the field hostingName for the document we’re updating

  3. updateObject — we pass in the $set operator to update the specified field.

Finally, the updateOne() method performs the update operation, passing in the query and updateObject objects.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

If you’d like to verify that the operation was a success, use the following command in the MongoDB shell:

1
db.webHostInfo.find({hostingName : "goDaddy"}).pretty()

You should get results that look something like this:

1
2
3
4
5
6
{
"_id" : ObjectId("5ce5e55c3fd48a0fa9e15386"),
"hostingName" : "goDaddy",
"number" : 1,
"location" : "USA"
}

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:

1
2
3
4
5
6
7
MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017");
MongoDatabase db = mongo.getDatabase("webHost");
BasicDBObject newDocument =
new BasicDBObject().append("$inc",
new BasicDBObject().append("number"6));

db.getCollection("webHostInfo").updateOne(new BasicDBObject().append("hostingName""webDotcom"), newDocument);

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:

1
2
3
4
5
6
7
8
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.append("location""USA");

BasicDBObject updateQuery = new BasicDBObject();
updateQuery.append("$set",
new BasicDBObject().append("number""888"));

db.getCollection("webHostInfo").updateMany(searchQuery, updateQuery);

The results that are returned should look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
{
"_id" : ObjectId("5ce5e55c3fd48a0fa9e15386"),
"hostingName" : "goDaddy",
"number" : "888",
"location" : "USA"
}
{
"_id" : ObjectId("5ce5e55c3fd48a0fa9e15387"),
"hostingName" : "Blue Host",
"number" : "888",
"location" : "USA"
}
{
"_id" : ObjectId("5ce5e55c3fd48a0fa9e15388"),
"hostingName" : "Just Host",
"number" : "888",
"location" : "USA"
}
{
"_id" : ObjectId("5ce5e55c3fd48a0fa9e15389"),
"hostingName" : "Rose Hosting",
"number" : "888",
"location" : "USA"
}
{
"_id" : ObjectId("5ce5e55c3fd48a0fa9e1538a"),
"hostingName" : "webDotcom",
"number" : "888",
"location" : "USA"
}

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

 

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
공지 오라클 기본 샘플 데이터베이스 졸리운_곰 2014.01.02 86847
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 79145
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95889
102 [MYSQL] 테이블 스키마 설계 고려사항 졸리운_곰 2022.12.03 1329
101 [MySQL] "아는 만큼 빨라진다" 마이SQL 성능 튜닝 팁 10가지 file 졸리운_곰 2022.11.29 1061
100 [Mysql] mysql에서 json 다루기 file 졸리운_곰 2022.08.02 1222
99 [MySQL] MySQL 에서 JSON Data사용하기 졸리운_곰 2022.08.02 1388
98 [MySQL] 관리자 root , admin 계정 추가 : MySQL 관리자 계정 추가 졸리운_곰 2021.09.26 9255
97 [MySQL] mysql 에서 컬럼과 로우 바꾸기, 행과 열 바꾸기 How to Transpose Rows to Columns Dynamically in MySQL file 졸리운_곰 2021.09.13 1037
96 [MySQL] MySQL ROLLUP , summary, 부분합 구하기 file 졸리운_곰 2021.09.01 1640
95 [mysql] 인덱스 정리 및 팁 file 졸리운_곰 2020.12.04 1393
94 [MySQL] 복제 지연 원인 및 해결 (reason for mysql replication lag/delay) file 졸리운_곰 2020.07.18 1409
93 MySQL Replication(복제) file 졸리운_곰 2020.07.18 1803
92 MySQL replication을 해보자 졸리운_곰 2020.07.18 1695
91 MySQL Replication(복제) - 단방향 이중화 file 졸리운_곰 2020.07.18 856
90 [MySQL] 행, 열 바꾸어 출력하기 CASE ~ AS file 졸리운_곰 2020.06.13 1040
89 [MySQL] 피벗 - 로우 데이터를 컬럼으로 옮기기 file 졸리운_곰 2020.06.13 1365
88 MySQL (or MariaDB) 에서 row 데이터를 column 으로 변경하기 졸리운_곰 2020.06.13 1342
87 [mysql] 운용 application 정보 (proxy, middle ware) 등: awesome-mysql file 졸리운_곰 2020.05.16 26550
86 [MySQL] 10장 여러 개의 테이블 이용하기 file 졸리운_곰 2020.05.16 1137
85 [MySQL] DB에 중복된 값의 개수를 확인하고 싶다. 졸리운_곰 2020.05.06 1187
84 sqlRelay(Mysql DB Pooling) 졸리운_곰 2020.02.17 1454
83 [참고자료] 공개커넥션풀 프로그램 졸리운_곰 2020.02.17 1988
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED