[mongodb , 몽고디비] How to Use MongoDB Comparison Query Operators in Java

Introduction

When you query a database, there are times when you need to use comparison operators to express the conditions of the query. You might want a list of all students whose age is greater than 16, or you might want the database to return all cars where the model year equals 2019. Queries like these are easy to create using MongoDB, but the exact syntax may be a bit unfamiliar if you’re used to working with SQL. In this step-by-step tutorial, we’ll provide instructions for using MongoDB comparison query operators in Java.

Prerequisites

Before we start looking at various comparison operators, it’s important to review the prerequisites for this task. There are a few key system requirements to consider:

  • You need to make sure that both MongoDB and the MongoDB Java driver are properly installed and configured.

  • You also need to confirm that the latest Java JDK has been installed and configured beforehand.

  • Finally, you need to confirm 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 version is 3.8.2.

The MongoDB Dataset

If you’re planning on following along with the examples in this article, it’s best to be working with the same dataset. We’ll be using the dataset shown below in this tutorial:

ID Name Rating Country
5ceb7d233fd48a1ebd04318e Chang Kai-shek 11 China
5ceb7d233fd48a1ebd04318f Sun Yat-sen 8 China
5ceb7d233fd48a1ebd043190 Muammar al-Gaddafi 15 Libya
5ceb7d233fd48a1ebd043191 Oda Nobunaga 15 Japan
5ceb7d233fd48a1ebd043192 Cao Cao 19 China
5ceb7d233fd48a1ebd043193 Sun Tzu 10 China

MongoDB Query Operators

MongoDB Query Operator $eq

The first operator we’ll be discussing is $eq. This operator denotes a equality condition. The $eq operator matches MongoDB documents where the value of a field equals the specified criteria.

Let’s look at an example of using the operator $eq in Java:

1
2
3
4
5
6
7
8
9
10
11
12
MongoDatabase db = mongo.getDatabase("warlordDB");

FindIterable<document> findIt = db.getCollection("warlordCollection").find(eq("name","Cao Cao"));

MongoCursor<document> cursor = findIt.iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}

NOTE : It’s recommended to include the static import for the method Filters.eq at the beginning of your code: import static com.mongodb.client.model.Filters.eq;.

The results should look like the following:

1
Document{{_id=5ceb7d233fd48a1ebd043192, name=Cao Cao, country=China}}

MongoDB Query Operator $gt

Next, we’ll look at the $gt operator. This operator selects documents where the field’s value is greater than the specified criteria. It’s similar to the >operator used in mathematics and SQL:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
MongoDatabase db = mongo.getDatabase("warlordDB");
FindIterable<document> findIt = db.getCollection("warlordCollection").find( new Document()
.append("rating"new Document()
.append("$gt" , 14)
));

MongoCursor<document> cursor = findIt.iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}

If we look at the dataset, we see that the results should look like the following, displaying all documents with a rating field greater than 14:

1
2
3
Document{{_id=5cebb0223fd48a338db1746d, name=Muammar al-Gaddafi, country=Libya, rating=15}}
Document{{_id=5cebb0223fd48a338db1746e, name=Oda Nobunaga, country=Japan, rating=15}}
Document{{_id=5cebb0223fd48a338db1746f, name=Cao Cao, country=China, rating=19}}

MongoDB Query Operator $lt

The operator $lt selects documents where the field’s value is less than the specified criteria. It’s similar to the < operator seen in mathematics and SQL:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
MongoDatabase db = mongo.getDatabase("warlordDB");
FindIterable<document> findIt = db.getCollection("warlordCollection").find( new Document()
.append("rating"new Document()
.append("$lt" , 14)
));

MongoCursor<document> cursor = findIt.iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}

In this example, we can look at our dataset and see that the result should look like the following, displaying all documents with a rating field less than 14:

1
2
3
Document{{_id=5cebb0223fd48a338db1746b, name=Chang Kai-shek, country=china, rating=11}}
Document{{_id=5cebb0223fd48a338db1746c, name=Sun Yat-sen, country=china, rating=8}}
Document{{_id=5cebb0223fd48a338db17470, name=Sun Tzu, country=China, rating=10}}

MongoDB Query Operator $gte

Now that we’ve covered “greater than” and “less than” operators, let’s move on to the $gte operator. This operator selects documents where the field’s value is greater than or equal to the specified criteria. In a SQL statement or mathematical expression, this operator would be represented as “>=”:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
MongoDatabase db = mongo.getDatabase("warlordDB");
FindIterable<document> findIt = db.getCollection("warlordCollection").find( new Document()
.append("rating"new Document()
.append("$gte" , 15)
));

MongoCursor<document> cursor = findIt.iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}

The code shown above returns documents that are greater than or equal to the value of the rating field.

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

The result will look something like this:

1
2
3
Document{{_id=5cebb0223fd48a338db1746d, name=Muammar al-Gaddafi, country=Libya, rating=15}}
Document{{_id=5cebb0223fd48a338db1746e, name=Oda Nobunaga, country=Japan, rating=15}}
Document{{_id=5cebb0223fd48a338db1746f, name=Cao Cao, country=China, rating=19}}

MongoDB Query Operator $lte

The operator $lte selects documents where the field’s value is less than or equal to the specified criteria. In a SQL statement or mathematical expression, this operator would be represented as “<=”:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
MongoDatabase db = mongo.getDatabase("warlordDB");
FindIterable<document> findIt = db.getCollection("warlordCollection").find( new Document()
.append("rating"new Document()
.append("$lte" , 15)
));

MongoCursor<document> cursor = findIt.iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}

The result should look something like this:

1
2
3
4
5
Document{{_id=5cebb0223fd48a338db1746b, name=Chang Kai-shek, country=china, rating=11}}
Document{{_id=5cebb0223fd48a338db1746c, name=Sun Yat-sen, country=china, rating=8}}
Document{{_id=5cebb0223fd48a338db1746d, name=Muammar al-Gaddafi, country=Libya, rating=15}}
Document{{_id=5cebb0223fd48a338db1746e, name=Oda Nobunaga, country=Japan, rating=15}}
Document{{_id=5cebb0223fd48a338db17470, name=Sun Tzu, country=China, rating=10}}

MongoDB Query Operator $in

Now, let’s look at a somewhat different type of operator: $in. The $in operator will select documents where the value of a field matches a value in a specified array (e.g. <value1><value2>, and so on). Let’s look at an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
MongoDatabase db = mongo.getDatabase("warlordDB");
FindIterable<document> findIt = db.getCollection("warlordCollection").find( new Document()
.append("rating"new Document()
.append("$in"Arrays.asList(19,10))
));

MongoCursor<document> cursor = findIt.iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}

In this query, we looked for documents where the value of rating matched one of the two values contained in the array [19,10]. The results should look something like this:

1
2
Document{{_id=5cebb0223fd48a338db1746f, name=Cao Cao, country=China, rating=19}}
Document{{_id=5cebb0223fd48a338db17470, name=Sun Tzu, country=China, rating=10}}

MongoDB Query Operator $nin

The $nin operator will simply select values that are not in the specified criteria:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
MongoDatabase db = mongo.getDatabase("warlordDB");
FindIterable<document> findIt = db.getCollection("warlordCollection").find( new Document()
.append("rating"new Document()
.append("$in"Arrays.asList(19,10))
));

MongoCursor<document> cursor = findIt.iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}

In this example, we’re looking for documents where the value of rating is not one of the values contained in the array [19, 10]. The result should look something like this:

1
2
3
4
Document{{_id=5cebb0223fd48a338db1746b, name=Chang Kai-shek, country=china, rating=11}}
Document{{_id=5cebb0223fd48a338db1746c, name=Sun Yat-sen, country=china, rating=8}}
Document{{_id=5cebb0223fd48a338db1746d, name=Muammar al-Gaddafi, country=Libya, rating=15}}
Document{{_id=5cebb0223fd48a338db1746e, name=Oda Nobunaga, country=Japan, rating=15}}

MongoDB Query Operator $ne

We began our examples with the $eq operator, and we’ll end with its opposite: the $ne operator. This operator simply selects values that are not equal to the specified criteria.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
MongoDatabase db = mongo.getDatabase("warlordDB");
FindIterable<document> findIt = db.getCollection("warlordCollection").find( new Document()
.append("rating"new Document()
.append("$ne"10)
));

MongoCursor<document> cursor = findIt.iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}

The result should look like the following:

1
2
3
4
5
Document{{_id=5cebb0223fd48a338db1746b, name=Chang Kai-shek, country=china, rating=11}}
Document{{_id=5cebb0223fd48a338db1746c, name=Sun Yat-sen, country=china, rating=8}}
Document{{_id=5cebb0223fd48a338db1746d, name=Muammar al-Gaddafi, country=Libya, rating=15}}
Document{{_id=5cebb0223fd48a338db1746e, name=Oda Nobunaga, country=Japan, rating=15}}
Document{{_id=5cebb0223fd48a338db1746f, name=Cao Cao, country=China, rating=19}}

Conclusion

Comparison operators are a staple of database queries, but the syntax used in MongoDB might seem a bit unfamiliar if you’re accustomed to SQL. Fortunately, the comparison query operators used in MongoDB are very easy to understand. With the examples and instructions provided in this tutorial, you’ll have no trouble using MongoDB comparison query operators in Java.

[출처] https://kb.objectrocket.com/mongo-db/how-to-use-mongodb-comparison-query-operators-in-java-382

 

 

 

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
공지 오라클 기본 샘플 데이터베이스 졸리운_곰 2014.01.02 86113
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 78624
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95338
46 [데이터분석 & 데이터 사이언스] 수많은 데이터 사이언티스트들이 직장을 떠나는 이유는 무엇인가? file 졸리운_곰 2025.03.09 901
45 [데이터분석][파이썬][python] 한글 글꼴 사용 (matplotlib) 졸리운_곰 2024.04.18 1360
44 [데이터분석 & 데이터 사이언스] 데이터에 관한 꼭 알아야 할 오해와 진실 12가지 졸리운_곰 2024.01.17 1315
43 [데이터분석][파이썬][python] Awesome Dash Awesome file 졸리운_곰 2021.07.10 2338
42 [데이터분석][파이썬][python] ???? Introducing Dash ???? file 졸리운_곰 2021.07.10 1606
41 [dataset] (한글) 욕설 감지 데이터셋 file 졸리운_곰 2021.05.12 1559
40 [데이터분석][python] Dash를 사용하는 초보자 및 기타 모든 사용자를위한 Python의 대시 보드 file 졸리운_곰 2021.04.14 1762
39 [데이터분석][python] Dash를 사용하는 초보자 및 기타 모든 사용자를위한 Python의 대시 보드 file 졸리운_곰 2021.04.14 1602
38 [데이터분석][데이터 사이언스][python][Dash] Python, Dash 및 Plotly를 사용하여 COVID-19 사례 데이터 시각화 file 졸리운_곰 2021.03.28 1501
37 [데이터분석][머신러닝] When not to use machine learning or AI Adventures in wishful thinking, nonstationarity, and pattern-finding / 기계 학습 또는 AI를 사용하지 않아야하는 경우 희망찬 사고, 비정상 성, 패턴 찾기의 모험 file 졸리운_곰 2021.03.28 21621
36 [MSA][머신러닝] 쿠버네티스 기반의 End2End 머신러닝 플랫폼 Kubeflow #1 - 소개 file 졸리운_곰 2021.03.21 1135
35 [데이터사이언스] 데이터 과학자를위한 3 가지 훌륭한 디자인 패턴, 3 Great Design Patterns for Data Scientists file 졸리운_곰 2021.03.04 779
34 [데이터분석] 시계열 데이터에 AI를 사용하는 이유는 무엇입니까? file 졸리운_곰 2021.02.28 1191
33 [데이터분석] AI 예측 및 이상 탐지를위한 시계열 데이터 전처리 file 졸리운_곰 2021.02.28 1031
32 [데이터분석] bitcoin analysis 비트 코인 시계열 데이터에 대한 AI 이상 탐지 file 졸리운_곰 2021.02.27 1588
31 [데이터분석 & 데이터 사이언스] How To Create a Data Science Portfolio Website file 졸리운_곰 2021.02.14 1823
30 [데이터수집4] 오픈 API 데이터 수집 (소셜미디어 데이터 수집) file 졸리운_곰 2020.06.12 1950
29 [데이터수집3] 관계형 데이터베이스 데이터 수집 file 졸리운_곰 2020.06.12 1317
28 [데이터수집2] 분산시스템 로그 수집 (빅데이터 수집) file 졸리운_곰 2020.06.12 1492
27 [데이터수집1] 웹 크롤링, 웹 스크래핑 file 졸리운_곰 2020.06.12 1804
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED