Computer >> 컴퓨터 >  >> 프로그래밍 >> MongoDB

MongoDB에서 특정 조건을 제외한 모든 문서 조회하기 – $ne와 $nin 연산자 활용법

MongoDB에서 전체 문서를 조회하되, 하나 또는 두 개의 특정 조건에 해당하는 문서만 제외하고 싶을 때가 있습니다. 이럴 때 사용할 수 있는 대표적인 방법은 $ne 연산자와 $nin 연산자입니다. 조건이 하나일 경우에는 $ne를, 조건이 두 개 이상일 경우에는 $nin을 사용하면 됩니다.

기본 쿼리 형식

Case 1: 단일 조건 제외 ($ne 연산자)

하나의 값만 제외하고 나머지 문서를 모두 가져오려면 $ne(not equal) 연산자를 사용합니다.

db.yourCollectionName.find({yourFieldName:{$ne:"yourValue"}}).pretty();

Case 2: 두 개의 조건 제외 ($nin 연산자)

두 개 이상의 값을 동시에 제외하려면 $nin(not in) 연산자를 사용합니다.

db.yourCollectionName.find({yourFieldName:{$nin:["yourValue1","yourValue2"]}}).pretty();

실습용 컬렉션 생성

실제 예제를 통해 확인해 보겠습니다. 먼저 샘플 문서들이 담긴 컬렉션을 생성합니다.

> db.findAllExceptFromOneOrtwoDemo.insertOne({"StudentName":"Larry","StudentSubjectName":"Java"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c993d82330fd0aa0d2fe4d2")
}
> db.findAllExceptFromOneOrtwoDemo.insertOne({"StudentName":"Chris","StudentSubjectName":"C++"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c993d8f330fd0aa0d2fe4d3")
}
> db.findAllExceptFromOneOrtwoDemo.insertOne({"StudentName":"Robert","StudentSubjectName":"C"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c993d99330fd0aa0d2fe4d4")
}
> db.findAllExceptFromOneOrtwoDemo.insertOne({"StudentName":"David","StudentSubjectName":"Python"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c993da4330fd0aa0d2fe4d5")
}

find() 메서드를 사용해 컬렉션의 모든 문서를 출력해 보겠습니다.

> db.findAllExceptFromOneOrtwoDemo.find().pretty();

실행 결과는 다음과 같습니다.

{
   "_id" : ObjectId("5c993d82330fd0aa0d2fe4d2"),
   "StudentName" : "Larry",
   "StudentSubjectName" : "Java"
}
{
   "_id" : ObjectId("5c993d8f330fd0aa0d2fe4d3"),
   "StudentName" : "Chris",
   "StudentSubjectName" : "C++"
}
{
   "_id" : ObjectId("5c993d99330fd0aa0d2fe4d4"),
   "StudentName" : "Robert",
   "StudentSubjectName" : "C"
}
{
   "_id" : ObjectId("5c993da4330fd0aa0d2fe4d5"),
   "StudentName" : "David",
   "StudentSubjectName" : "Python"
}

Case 1: 단일 조건 제외하기

과목명(StudentSubjectName)이 "C"가 아닌 문서만 조회하는 쿼리입니다.

> db.findAllExceptFromOneOrtwoDemo.find({StudentSubjectName:{$ne:"C"}}).pretty();

실행 결과, "C" 과목을 수강하는 Robert의 문서가 제외된 것을 확인할 수 있습니다.

{
   "_id" : ObjectId("5c993d82330fd0aa0d2fe4d2"),
   "StudentName" : "Larry",
   "StudentSubjectName" : "Java"
}
{
   "_id" : ObjectId("5c993d8f330fd0aa0d2fe4d3"),
   "StudentName" : "Chris",
   "StudentSubjectName" : "C++"
}
{
   "_id" : ObjectId("5c993da4330fd0aa0d2fe4d5"),
   "StudentName" : "David",
   "StudentSubjectName" : "Python"
}

Case 2: 두 개의 조건 제외하기

이번에는 과목명이 "C++" 또는 "Python"인 문서를 모두 제외하고 조회해 보겠습니다.

> db.findAllExceptFromOneOrtwoDemo.find({StudentSubjectName:{$nin:["C++","Python"]}}).pretty();

실행 결과, Chris(C++)와 David(Python)의 문서가 제외되고 Larry(Java)와 Robert(C)의 문서만 반환됩니다.

{
   "_id" : ObjectId("5c993d82330fd0aa0d2fe4d2"),
   "StudentName" : "Larry",
   "StudentSubjectName" : "Java"
}
{
   "_id" : ObjectId("5c993d99330fd0aa0d2fe4d4"),
   "StudentName" : "Robert",
   "StudentSubjectName" : "C"
}

정리

이처럼 MongoDB에서 특정 값을 제외한 문서를 조회할 때는 다음과 같이 정리할 수 있습니다.

  • 조건이 하나일 때: $ne 연산자를 사용하여 해당 값과 일치하지 않는 문서를 조회
  • 조건이 두 개 이상일 때: $nin 연산자에 배열 형태로 여러 값을 지정하여 일괄 제외

두 연산자 모두 인덱스가 설정된 필드에 사용하면 성능 저하 없이 효율적으로 활용할 수 있으므로, 실무에서 데이터 필터링 시 유용하게 사용됩니다.