MongoDB에서 특정 레코드와 일치하는 정규식 사용 방법
MongoDB에서는 정규식(Regular Expression)을 활용하면 대소문자를 구분하여 원하는 레코드만 정확하게 조회할 수 있습니다. 이번 글에서는 예제를 통해 특정 레코드와 일치하는 문서를 찾는 방법을 단계별로 살펴보겠습니다.
1단계: 샘플 데이터로 컬렉션 생성
먼저 insertOne() 메서드를 사용하여 문서가 포함된 컬렉션을 생성합니다. 여기서는 학생 이름이 'John', 'JOHN', 'Carol'인 세 개의 문서를 삽입합니다.
> db.workingOfRegularExpressionDemo.insertOne({ "StudentDetails" : { "StudentName" : "John" }, "StudentAge": 21 });
{
"acknowledged" : true,
"insertedId" : ObjectId("5cf227acb64a577be5a2bc07")
}
> db.workingOfRegularExpressionDemo.insertOne({ "StudentDetails" : { "StudentName" : "JOHN" }, "StudentAge": 19 });
{
"acknowledged" : true,
"insertedId" : ObjectId("5cf227b8b64a577be5a2bc08")
}
> db.workingOfRegularExpressionDemo.insertOne({ "StudentDetails" : { "StudentName" : "Carol" }, "StudentAge": 20 });
{
"acknowledged" : true,
"insertedId" : ObjectId("5cf227c2b64a577be5a2bc09")
}2단계: find() 메서드로 전체 문서 확인
find() 메서드를 사용하면 컬렉션에 저장된 모든 문서를 조회할 수 있습니다.
> db.workingOfRegularExpressionDemo.find();
위 쿼리를 실행하면 다음과 같은 결과가 출력됩니다.
{ "_id" : ObjectId("5cf227acb64a577be5a2bc07"), "StudentDetails" : { "StudentName" : "John" }, "StudentAge" : 21 }
{ "_id" : ObjectId("5cf227b8b64a577be5a2bc08"), "StudentDetails" : { "StudentName" : "JOHN" }, "StudentAge" : 19 }
{ "_id" : ObjectId("5cf227c2b64a577be5a2bc09"), "StudentDetails" : { "StudentName" : "Carol" }, "StudentAge" : 20 }3단계: 정규식으로 특정 레코드 조회
이제 정규식을 사용하여 StudentName이 'JOHN'인 문서만 조회해 보겠습니다. MongoDB에서는 슬래시(/)로 감싼 패턴을 통해 정규식 조건을 지정할 수 있습니다.
> db.workingOfRegularExpressionDemo.find({'StudentDetails.StudentName': /JOHN/});실행 결과, 이름이 정확히 'JOHN'인 문서 하나만 반환됩니다.
{ "_id" : ObjectId("5cf227b8b64a577be5a2bc08"), "StudentDetails" : { "StudentName" : "JOHN" }, "StudentAge" : 19 }참고: 대소문자 구분 없이 검색하기
만약 대소문자와 관계없이 'john'이라는 이름을 모두 찾고 싶다면, 정규식 옵션 'i'를 추가하면 됩니다.
> db.workingOfRegularExpressionDemo.find({'StudentDetails.StudentName': /john/i});이 경우 'John'과 'JOHN' 두 문서가 모두 조회됩니다. 이처럼 MongoDB의 정규식 기능을 활용하면 중첩된 문서 내부의 문자열 필드까지 유연하고 강력하게 검색할 수 있습니다.