[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 86794
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 79094
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95855
42 블록체인 기반 플랫폼 비즈니스를 이해하자 졸리운_곰 2017.09.10 1556
41 다운타임 없는 서비스 구현 패턴 file 졸리운_곰 2017.09.10 1232
40 테이블의 수직분할과 수평분할에 대한 이해 file 졸리운_곰 2017.09.10 3913
39 정규화와 응집도에 대한 고찰 file 졸리운_곰 2017.05.28 1789
38 머신러닝 새 도전…“클라우드를 벗어나라" file 졸리운_곰 2017.05.28 1714
37 보안성 높이는 공공 거래장부 블록체인 file 졸리운_곰 2017.05.28 1769
36 디지털, 속도의 전쟁 VS 데이터, 품질의 전쟁 file 졸리운_곰 2017.05.05 1520
35 04. 데이터 모델링의 3단계 진행 file 졸리운_곰 2016.03.15 1664
34 데이터베이스 설계의 기본 원리.pdf file 졸리운_곰 2016.03.15 2358
33 실체유형(Entity Type) 정의 사항 및 도출 file 졸리운_곰 2015.05.21 2199
32 마농의 SQL 백문백답: 단순하고 쉽게 작성하는 SQL 노하우 [1회] file 졸리운_곰 2015.05.21 1834
31 sql개발자-sql전문가자격시험 시험 예제.pdf file 졸리운_곰 2015.02.15 2307
30 데이터베이스 선정에는 비밀이 있다 - 4부 졸리운_곰 2015.01.15 2102
29 데이터베이스 선정에는 비밀이 있다 - 3부 졸리운_곰 2015.01.15 2050
28 데이터베이스 선정에는 비밀이 있다 - 2부 졸리운_곰 2015.01.15 1830
27 데이터베이스 선정에는 비밀이 있다 - 1부 졸리운_곰 2015.01.15 2400
26 지금 우리에게 필요한 것은 데이터베이스 성능 최적화이다 (2부) 졸리운_곰 2015.01.15 1493
25 우리에게 필요한 것은 데이터베이스 성능 (1부) 졸리운_곰 2015.01.15 1794
24 21회 결과 secret 졸리운_곰 2014.11.10 0
23 [데이터아키텍쳐준전문가] 시험 fail 자료 secret 졸리운_곰 2014.08.31 0
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED