본문 바로가기
noSQL

MongoDB에서 문서 조회 비교 연산자 예제

by 피이웅콱푸지이삐용삐용지요지용뿌에에콱 2024. 7. 3.

MongoDB에서 문서를 조회할 때 사용할 수 있는 다양한 비교 연산자가 있습니다. 이 연산자들은 특정 조건에 맞는 문서를 필터링하는 데 사용됩니다.

 

비교 연산자 목록

  1. $eq (equal)
  2. $ne (not equal)
  3. $gt (greater than)
  4. $gte (greater than or equal)
  5. $lt (less than)
  6. $lte (less than or equal)
  7. $in (in array)
  8. $nin (not in array)

 

사용 예시

 

$eq (equal)

특정 필드가 주어진 값과 같은 문서를 찾습니다.

db.collection.find({ field: { $eq: value } })

예제:
db.users.find({ age: { $eq: 25 } })

 

$ne (not equal)

특정 필드가 주어진 값과 같지 않은 문서를 찾습니다.

db.collection.find({ field: { $ne: value } })

예제:
db.users.find({ age: { $ne: 25 } })

 

$gt (greater than)

특정 필드가 주어진 값보다 큰 문서를 찾습니다.

db.collection.find({ field: { $gt: value } })

예제:
db.users.find({ age: { $gt: 25 } })​

 

$gte (greater than or equal)

특정 필드가 주어진 값보다 크거나 같은 문서를 찾습니다.

db.collection.find({ field: { $gte: value } })

예제:
db.users.find({ age: { $gte: 25 } })

$lt (less than)

특정 필드가 주어진 값보다 작은 문서를 찾습니다.

db.collection.find({ field: { $lt: value } })

예제:
db.users.find({ age: { $lt: 25 } })
 

$lte (less than or equal)

특정 필드가 주어진 값보다 작거나 같은 문서를 찾습니다.

db.collection.find({ field: { $lte: value } })

예제:
db.users.find({ age: { $lte: 25 } })
 

$in (in array)

특정 필드가 주어진 배열의 값들 중 하나와 일치하는 문서를 찾습니다.

db.collection.find({ field: { $in: [value1, value2, ...] } })

예제:
db.users.find({ age: { $in: [25, 30, 35] } })
 

$nin (not in array)

특정 필드가 주어진 배열의 값들 중 어느 하나와도 일치하지 않는 문서를 찾습니다.

db.collection.find({ field: { $nin: [value1, value2, ...] } })

예제:
db.users.find({ age: { $nin: [25, 30, 35] } })
 

복합 예제

여러 비교 연산자를 조합하여 사용할 수도 있습니다.

db.users.find({ 
 age: { $gte: 25, $lte: 35 }, 
 status: { $ne: "inactive" }, 
 tags: { $in: ["developer", "admin"] } 
})
 

'noSQL' 카테고리의 다른 글

mongoDB - pymongo ObjectId 사용하기  (0) 2022.09.20