[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 86823
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 79118
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95875
78 [Kafka] Kafka 한번 살펴보자... Quickstart file 졸리운_곰 2021.06.18 1313
77 Java Kafka Producer, Consumer 예제 구현 Java를 이용하여 Kafka Producer와 Kakfa Consumer를 구현해보자. file 졸리운_곰 2021.06.18 1172
76 Beginner’s Guide to Understand Kafka file 졸리운_곰 2021.06.18 1575
75 [Kafka] Kafka 설치/실행 및 테스트 file 졸리운_곰 2021.06.18 1066
74 [java] [kafka] [Kafka] 개념 및 기본예제 file 졸리운_곰 2021.06.16 2170
73 Getting started with Apache Kafka in Python file 졸리운_곰 2020.09.10 2261
72 [Kafka] 다운로드 및 Quick Start file 졸리운_곰 2020.09.07 1899
71 [Kafka] 기본 개념잡기 file 졸리운_곰 2020.09.07 1713
70 Flume Integration with Kafka file 졸리운_곰 2019.04.16 2084
69 빅데이터: 플럼(Flume) 토폴로지 설계 file 졸리운_곰 2019.04.16 1604
68 실시간 처리를 위한 분산 메시징 시스템 카프카(Kafka) file 졸리운_곰 2018.05.12 1410
67 Flume과 Kafka를 사용한 초당 100만개 로그 수집 테스트 file 졸리운_곰 2018.05.12 1402
66 웹 크롤링 / web crwaling / web scraping / 웹 스크래핑 file 졸리운_곰 2017.07.09 1848
65 빅데이터 단지 몇퍼센트의 예측 정확성을 위하여 장애로 가득찬 빅데이터 시스템을 도입하여야 하는가에 대한 의문! file 졸리운_곰 2017.03.20 1609
64 빅데이터: 플럼(Flume) 토폴로지 설계 file 졸리운_곰 2017.03.20 1421
63 [실시간 분석 시스템] Apache Flume를 활용한 데이터 수집(1) file 졸리운_곰 2017.03.06 1322
62 [실시간 분석 시스템] 데이터 수집 #2 Apache Sqoop을 활용하여 RDBMS 데이터 수집(2) file 졸리운_곰 2017.03.06 1386
61 [실시간 분석 시스템] 데이터 수집 #2 Apache Sqoop을 활용하여 RDBMS 데이터 수집(1) file 졸리운_곰 2017.03.06 1109
60 [실시간 분석 시스템] 데이터 수집 #1 오픈 소스 수집기 비교 file 졸리운_곰 2017.03.06 1750
59 [실시간 분석 시스템] 일단 데이터 들여다 보기 file 졸리운_곰 2017.03.06 1947
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED