[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 86763
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 79078
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95841
864 [러닝 텐서플로]Chap06 - 텍스트2: word2vec, Bidirectional RNN, GRU, 임베딩 시각화 file 졸리운_곰 2020.12.28 1289
863 [러닝 텐서플로]Chap05 - 텍스트 1: 텍스트와 시퀀스 처리 및 텐서보드 시각화 file 졸리운_곰 2020.12.28 1060
862 [러닝 텐서플로]Chap04 - 합성곱 신경망 CNN file 졸리운_곰 2020.12.28 1148
861 Making TensorFlow Models Portable Using ONNX file 졸리운_곰 2020.12.24 4435
860 [러닝 텐서플로]Chap03 - 텐서플로의 기본 이해하기 file 졸리운_곰 2020.12.24 1476
859 [러닝 텐서플로]Chap02 - 텐서플로 설치 및 실행 file 졸리운_곰 2020.12.24 851
858 [러닝 텐서플로]Chap01 - 텐서플로 란? file 졸리운_곰 2020.12.24 1279
857 러닝 텐서플로 - 0 file 졸리운_곰 2020.12.24 1787
856 Prometheus Query(PromQL) 기본 이해하기 file 졸리운_곰 2020.12.17 1416
855 [인프라 모니터링 오픈소스] Prometheus 를 알아보자 file 졸리운_곰 2020.12.17 1913
854 Prometheus + Grafana 대시보드 file 졸리운_곰 2020.12.17 2493
853 Grafana란? file 졸리운_곰 2020.12.17 2162
852 [mongodb] Error: network error while attempting to run command 'isMaster' on host '127.0.0.1:27017' file 졸리운_곰 2020.12.16 1450
» [mongodb] How to Update a Document in MongoDB using Java 졸리운_곰 2020.12.14 2334
850 [oracle] 오라클 merge into 간단설명 및 예제(sample) 졸리운_곰 2020.12.14 1151
849 [oracle, sql] 04 | MERGE문 졸리운_곰 2020.12.14 1166
848 통계분석툴 R & MongoDB 연동 방법 file 졸리운_곰 2020.12.12 1829
847 [오라클, oracle] ORA-00911 : 문자가 부적합합니다 v1.0 졸리운_곰 2020.12.11 1756
846 [oracle, 오라클] 테이블이 존재 하는데, ORA-00942 발생 file 졸리운_곰 2020.12.11 4057
845 [Java, MongoDB] Mapping a BSON MongoDB document to a MyClass.class object? 졸리운_곰 2020.12.09 1822
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED