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

MongoDB에서 NOT LIKE 연산자 사용하는 방법 – $not 연산자로 특정 패턴 제외하기

MongoDB에서 NOT LIKE 연산자 사용하기: $not 연산자 활용법

SQL에 익숙한 개발자라면 특정 패턴과 일치하지 않는 데이터를 조회할 때 NOT LIKE 연산자를 자주 사용하게 됩니다. MongoDB에는 이름이 같은 연산자는 존재하지 않지만, $not 연산자를 정규 표현식과 조합하면 완전히 동일한 결과를 얻을 수 있습니다.

개념을 확실히 이해할 수 있도록 샘플 컬렉션을 만들고 단계별로 살펴보겠습니다.

1단계: 컬렉션 생성 및 문서 삽입

먼저 insertOne() 메서드를 사용해 notLikeOperatorDemo 컬렉션에 학생 이름 데이터를 하나씩 삽입합니다.

> db.notLikeOperatorDemo.insertOne({"StudentName":"John Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a29c393b406bd3df60dfc")
}
> db.notLikeOperatorDemo.insertOne({"StudentName":"John Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a29cc93b406bd3df60dfd")
}
> db.notLikeOperatorDemo.insertOne({"StudentName":"John Taylor"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a29df93b406bd3df60dfe")
}
> db.notLikeOperatorDemo.insertOne({"StudentName":"Carol Taylor"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a2a1693b406bd3df60dff")
}
> db.notLikeOperatorDemo.insertOne({"StudentName":"David Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a2a2693b406bd3df60e00")
}

2단계: find() 메서드로 전체 문서 확인

find() 메서드에 pretty()를 함께 사용하면 컬렉션에 저장된 모든 문서를 보기 좋게 출력할 수 있습니다.

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

실행 결과는 다음과 같습니다. 총 5개의 문서가 저장되어 있는 것을 확인할 수 있습니다.

{ "_id" : ObjectId("5c8a29c393b406bd3df60dfc"), "StudentName" : "John Doe" }
{
   "_id" : ObjectId("5c8a29cc93b406bd3df60dfd"),
   "StudentName" : "John Smith"
}
{
   "_id" : ObjectId("5c8a29df93b406bd3df60dfe"),
   "StudentName" : "John Taylor"
}
{
   "_id" : ObjectId("5c8a2a1693b406bd3df60dff"),
   "StudentName" : "Carol Taylor"
}
{
   "_id" : ObjectId("5c8a2a2693b406bd3df60e00"),
   "StudentName" : "David Miller"
}

3단계: $not 연산자로 NOT LIKE 쿼리 작성

이제 핵심 단계입니다. "John Taylor"라는 문자열로 시작하는 문서를 제외한 나머지 문서만 조회해 보겠습니다. $not 연산자 내부에 정규 표현식을 지정하면 됩니다.

> db.notLikeOperatorDemo.find( { StudentName: { $not: /^John Taylor.*/ } } );

"John Taylor" 문서 하나가 걸러지고 나머지 4개의 문서가 반환됩니다.

{ "_id" : ObjectId("5c8a29c393b406bd3df60dfc"), "StudentName" : "John Doe" }
{ "_id" : ObjectId("5c8a29cc93b406bd3df60dfd"), "StudentName" : "John Smith" }
{ "_id" : ObjectId("5c8a2a1693b406bd3df60dff"), "StudentName" : "Carol Taylor" }
{ "_id" : ObjectId("5c8a2a2693b406bd3df60e00"), "StudentName" : "David Miller" }

부분 문자열 매칭으로 조회하기

문자열 시작 위치를 의미하는 앵커(^) 없이, 단순 부분 문자열 매칭 방식으로도 동일한 결과를 얻을 수 있습니다.

> db.notLikeOperatorDemo.find({StudentName: {$not: /John Taylor/}});

실행 결과:

{ "_id" : ObjectId("5c8a29c393b406bd3df60dfc"), "StudentName" : "John Doe" }
{ "_id" : ObjectId("5c8a29cc93b406bd3df60dfd"), "StudentName" : "John Smith" }
{ "_id" : ObjectId("5c8a2a1693b406bd3df60dff"), "StudentName" : "Carol Taylor" }
{ "_id" : ObjectId("5c8a2a2693b406bd3df60e00"), "StudentName" : "David Miller" }

참고: 대소문자 구분 없이 조회하기

정규 표현식에 i 옵션 플래그를 추가하면 대소문자를 구분하지 않고 패턴을 제외할 수 있습니다.

> db.notLikeOperatorDemo.find({StudentName: {$not: /john taylor/i}});

정리

MongoDB에서 SQL의 NOT LIKE와 같은 동작이 필요하다면 { 필드명: { $not: /정규표현식/ } } 형태를 기억하면 됩니다. $not 연산자는 뒤에 오는 조건(여기서는 정규 표현식 매칭)의 결과를 반전시키는 역할을 하므로, 원하는 패턴을 정규 표현식으로 작성하기만 하면 해당 패턴에 일치하지 않는 문서를 손쉽게 조회할 수 있습니다.