MongoDB에서 정수(Integer) 값에 대해 정규식 검색을 수행하려면 일반적인 $regex 방식 대신 $where 연산자를 사용해야 합니다. 정규식은 기본적으로 문자열에 적용되기 때문에, 숫자 필드를 대상으로 패턴 매칭을 하려면 JavaScript 표현식을 활용하는 $where 접근이 필요합니다.
기본 문법
db.yourCollectionName.find({ $where:
"/^yourIntegerPatternValue.*/.test(this.yourFieldName)" });위 문법에서 yourIntegerPatternValue는 찾고자 하는 숫자 패턴이고, this.yourFieldName은 검색 대상이 되는 숫자 필드입니다. .test() 메서드는 해당 필드의 값이 주어진 정규식 패턴과 일치하는지 확인합니다.
예제 컬렉션 생성하기
개념을 이해하기 위해 먼저 문서가 포함된 컬렉션을 만들어 보겠습니다.
> db.regExpOnIntegerDemo.insertOne({"StudentId":2341234});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c70370c75eb1743ddddce21")
}
> db.regExpOnIntegerDemo.insertOne({"StudentId":123234});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c70371175eb1743ddddce22")
}
> db.regExpOnIntegerDemo.insertOne({"StudentId":9871234});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c70371875eb1743ddddce23")
}
> db.regExpOnIntegerDemo.insertOne({"StudentId":2345612});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c70372275eb1743ddddce24")
}
> db.regExpOnIntegerDemo.insertOne({"StudentId":1239812345});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c70372975eb1743ddddce25")
}저장된 전체 문서 조회하기
find() 메서드를 사용해 컬렉션의 모든 문서를 출력할 수 있습니다.
> db.regExpOnIntegerDemo.find().pretty();
실행 결과는 다음과 같습니다.
{ "_id" : ObjectId("5c70370c75eb1743ddddce21"), "StudentId" : 2341234 }
{ "_id" : ObjectId("5c70371175eb1743ddddce22"), "StudentId" : 123234 }
{ "_id" : ObjectId("5c70371875eb1743ddddce23"), "StudentId" : 9871234 }
{ "_id" : ObjectId("5c70372275eb1743ddddce24"), "StudentId" : 2345612 }
{ "_id" : ObjectId("5c70372975eb1743ddddce25"), "StudentId" : 1239812345 }정수 값에 정규식 검색 실행하기
이제 $where 연산자를 사용해 123으로 시작하는 StudentId를 검색하는 쿼리를 실행해 보겠습니다.
> db.regExpOnIntegerDemo.find({ $where: "/^123.*/.test(this.StudentId)" });실행 결과는 다음과 같습니다.
{ "_id" : ObjectId("5c70371175eb1743ddddce22"), "StudentId" : 123234 }
{ "_id" : ObjectId("5c70372975eb1743ddddce25"), "StudentId" : 1239812345 }결과를 보면 123234와 1239812345, 즉 123으로 시작하는 두 개의 문서만 반환된 것을 확인할 수 있습니다.
주의 사항
$where 연산자는 각 문서마다 JavaScript를 실행하기 때문에 인덱스를 활용할 수 없으며, 대용량 컬렉션에서는 성능 저하가 발생할 수 있습니다. 따라서 프로덕션 환경에서는 가능한 한 데이터를 문자열로 저장하거나, 애플리케이션 레벨에서 필터링하는 방식을 고려하는 것이 좋습니다.