[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 86873
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 79171
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95908
46 [데이터분석 & 데이터 사이언스] 수많은 데이터 사이언티스트들이 직장을 떠나는 이유는 무엇인가? file 졸리운_곰 2025.03.09 907
45 [데이터분석][파이썬][python] 한글 글꼴 사용 (matplotlib) 졸리운_곰 2024.04.18 1362
44 [데이터분석 & 데이터 사이언스] 데이터에 관한 꼭 알아야 할 오해와 진실 12가지 졸리운_곰 2024.01.17 1317
43 [데이터분석][파이썬][python] Awesome Dash Awesome file 졸리운_곰 2021.07.10 2345
42 [데이터분석][파이썬][python] ???? Introducing Dash ???? file 졸리운_곰 2021.07.10 1610
41 [dataset] (한글) 욕설 감지 데이터셋 file 졸리운_곰 2021.05.12 1560
40 [데이터분석][python] Dash를 사용하는 초보자 및 기타 모든 사용자를위한 Python의 대시 보드 file 졸리운_곰 2021.04.14 1767
39 [데이터분석][python] Dash를 사용하는 초보자 및 기타 모든 사용자를위한 Python의 대시 보드 file 졸리운_곰 2021.04.14 1605
38 [데이터분석][데이터 사이언스][python][Dash] Python, Dash 및 Plotly를 사용하여 COVID-19 사례 데이터 시각화 file 졸리운_곰 2021.03.28 1504
37 [데이터분석][머신러닝] When not to use machine learning or AI Adventures in wishful thinking, nonstationarity, and pattern-finding / 기계 학습 또는 AI를 사용하지 않아야하는 경우 희망찬 사고, 비정상 성, 패턴 찾기의 모험 file 졸리운_곰 2021.03.28 21624
36 [MSA][머신러닝] 쿠버네티스 기반의 End2End 머신러닝 플랫폼 Kubeflow #1 - 소개 file 졸리운_곰 2021.03.21 1141
35 [데이터사이언스] 데이터 과학자를위한 3 가지 훌륭한 디자인 패턴, 3 Great Design Patterns for Data Scientists file 졸리운_곰 2021.03.04 783
34 [데이터분석] 시계열 데이터에 AI를 사용하는 이유는 무엇입니까? file 졸리운_곰 2021.02.28 1195
33 [데이터분석] AI 예측 및 이상 탐지를위한 시계열 데이터 전처리 file 졸리운_곰 2021.02.28 1038
32 [데이터분석] bitcoin analysis 비트 코인 시계열 데이터에 대한 AI 이상 탐지 file 졸리운_곰 2021.02.27 1600
31 [데이터분석 & 데이터 사이언스] How To Create a Data Science Portfolio Website file 졸리운_곰 2021.02.14 1834
30 [데이터수집4] 오픈 API 데이터 수집 (소셜미디어 데이터 수집) file 졸리운_곰 2020.06.12 1955
29 [데이터수집3] 관계형 데이터베이스 데이터 수집 file 졸리운_곰 2020.06.12 1321
28 [데이터수집2] 분산시스템 로그 수집 (빅데이터 수집) file 졸리운_곰 2020.06.12 1499
27 [데이터수집1] 웹 크롤링, 웹 스크래핑 file 졸리운_곰 2020.06.12 1806
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED