참고
이 페이지에서는 자체 관리(비Atlas) 배포를 위한 일반 표현식 검색 역량에 대해 설명합니다. MongoDB Atlas에 호스팅된 데이터의 경우 MongoDB는 자체 $regex 연산자가 있는 향상된 전체 텍스트 검색 솔루션인 Atlas Search를 제공합니다. 자세히 알아보려면 Atlas Search 설명서에서 $regex를 참조하세요.
정의
호환성
다음 환경에서 호스팅되는 배포에 $regex 사용할 수 있습니다.
MongoDB Atlas: 클라우드에서의 MongoDB 배포를 위한 완전 관리형 서비스
MongoDB Enterprise: MongoDB의 구독 기반 자체 관리 버전
MongoDB Community: MongoDB의 소스 사용 가능 무료 자체 관리 버전
구문
Use one of the following syntax variations:
{ <field>: { $regex: /pattern/, $options: '<options>' } } { "<field>": { "$regex": "pattern", "$options": "<options>" } } { <field>: { $regex: /pattern/<options> } }
참고
To use $regex with mongodump, enclose the query document in single quotes ('{ ... }') to ensure it doesn't interact with the shell.
쿼리 문서는 필드 이름과 연산자를 따옴표로 묶는 등 확장 JSON v2 형식 (완화 모드 또는 표준/엄격 모드)이어야 합니다. 예시:
mongodump -d=sample_mflix -c=movies -q='{"year": {"$regex": "20"}}'
You can also use regular expression objects (/pattern/) to specify regular expressions:
{ <field>: /pattern/<options> }
For restrictions on syntax use, see $regex vs. /pattern/ Syntax.
The following <options> are available for regular expressions:
옵션 | 설명 |
|---|---|
| 대소문자를 구분하지 않고 대문자와 소문자를 일치시킵니다. 예시 는 대소문자를 구분하지 않는 정규 표현식 일치 수행하기를 참조하세요. |
| For patterns that include anchors ( If the pattern has no anchors or if the string value has no newline characters (for example, |
|
또한 이스케이프되지 않은 해시/파운드 ( The |
| Allows the dot character ( |
| Unicode option, which is accepted but redundant. UTF is enabled by default for |
참고
$regex doesn't support the global search modifier g.
행동
정규식 대 /패턴/ 구문
$in 표현식
$in 쿼리 조건자 연산자에 정규 표현식을 포함하려면 JavaScript 정규 표현식 객체(/pattern/)만 사용할 수 있습니다.
예를 들면 다음과 같습니다.
{ name: { $in: [ /^acme/i, /^ack/ ] } }
$in 연산자 내에서 $regex연산자 표현식을 사용할 수 없습니다 .
필드에 대한 암시적 AND 조건
필드에 대한 쉼표로 구분된 쿼리 조건 목록에 정규 표현식을 포함하려면 $regex 연산자를 사용합니다. 예시:
{ name: { $regex: /acme.*corp/i, $nin: [ 'acmeblahcorp' ] } } { name: { $regex: /acme.*corp/, $options: 'i', $nin: [ 'acmeblahcorp' ] } } { name: { $regex: 'acme.*corp', $options: 'i', $nin: [ 'acmeblahcorp' ] } }
x 및 s 옵션
x 옵션 또는 s 옵션을 사용하려면 $regex 연산자 표현식을 $options 연산자와 함께 사용해야 합니다. 예를 들어 i 및 s 옵션을 지정하려면 두 옵션 모두에 $options를 사용해야 합니다.
{ name: { $regex: /acme.*corp/, $options: "si" } } { name: { $regex: 'acme.*corp', $options: "si" } }
PCRE와 JavaScript 비교
To use PCRE-supported features in a regular expression that aren't supported in JavaScript, use the $regex operator and specify the pattern as a string.
대소문자를 구분하지 않는 문자열을 일치시키려면 다음을 수행하십시오.
"(?i)"대/소문자를 구분하지 않는 일치를 시작합니다."(?-i)"대/소문자를 구분하지 않는 일치를 종료합니다.
예를 들어 표현식 "(?i)a(?-i)cme" 은(는) 다음과 같은 문자열과 일치합니다.
"a"또는"A"으로 시작합니다. 대소문자를 구분하지 않는 일치입니다."cme"로 끝납니다. 대소문자를 구분하는 일치 항목입니다.
이러한 문자열은 표현식과 일치합니다:
"acme""Acme"
다음 예시에서는 $regex 연산자를 사용하여 정규 표현식 "(?i)a(?-i)cme" 와(과) 일치하는 name 필드 문자열을 찾습니다.
{ name: { $regex: "(?i)a(?-i)cme" } }
버전 6.1부터 MongoDB는 PCRE2(Perl 호환 정규 표현식) 라이브러리를 사용하여 정규 표현식 패턴 일치를 구현합니다. PCRE 2에 대한 자세한 내용은 PCRE 설명서를 참조하세요.
$regex 개인정보 정책에 $not
The $not operator can perform a logical NOT operation on both:
Regular expression objects (
/pattern/)예를 들면 다음과 같습니다.
db.inventory.find( { item: { $not: /^p.*/ } } ) $regex연산자 표현식예를 들면 다음과 같습니다.
db.inventory.find( { item: { $not: { $regex: "^p.*" } } } ) db.inventory.find( { item: { $not: { $regex: /^p.*/ } } } )
인덱스 사용하기
Index use and performance for $regex queries depends on whether the query is case-sensitive or case-insensitive.
대소문자를 구분하는 쿼리
For case sensitive regular expression queries, if an index exists for the field, then MongoDB matches the regular expression for the values in the index. This can be faster than a collection scan.
Further optimization can occur if the regular expression is a "prefix expression", which means that all potential matches start with the same string. This allows MongoDB to construct a "range" from that prefix and only match values from the index within the specified range.
A regular expression is a "prefix expression" if it starts with a caret (^) or a left anchor (\A), followed by a string of simple symbols. For example, the regex /^abc.*/ is optimized to match only the values from the index that start with abc.
Additionally, although /^a/, /^a.*/, and /^a.*$/ match equivalent strings, they have different performance characteristics. All of these expressions use an index if an appropriate index exists. However, /^a.*/, and /^a.*$/ are slower. /^a/ can stop scanning after matching the prefix.
대소문자를 구분하지 않는 쿼리
$regex 연산자는 데이터 정렬을 인식하지 않으므로 이러한 인덱스를 활용할 수 없기 때문에 대소문자를 구분하지 않는 인덱스는 $regex 쿼리의 성능을 향상시키지 않습니다.
예시
이 섹션의 예시에서는 다음의 products collection을 사용합니다.
db.products.insertMany( [ { _id: 100, sku: "abc123", description: "Single line description." }, { _id: 101, sku: "abc789", description: "First line\nSecond line" }, { _id: 102, sku: "xyz456", description: "Many spaces before line" }, { _id: 103, sku: "xyz789", description: "Multiple\nline description" }, { _id: 104, sku: "Abc789", description: "SKU starts with A" } ] )
LIKE 매치 수행
다음 예시는 sku 필드가 "%789" 과 같은 모든 문서와 일치합니다.
db.products.find( { sku: { $regex: /789$/ } } )
The example is similar to the following SQL LIKE statement:
SELECT * FROM products WHERE sku like "%789";
출력 예시:
[ { _id: 101, sku: 'abc789', description: 'First line\nSecond line' }, { _id: 103, sku: 'xyz789', description: 'Multiple\nline description' }, { _id: 104, sku: 'Abc789', description: 'SKU starts with A' } ]
대소문자를 구분하지 않는 정규식 일치 수행
The following example uses the i option to perform a case-insensitive match for sku values that start with ABC:
db.products.find( { sku: { $regex: /^ABC/i } } )
출력 예시:
[ { _id: 100, sku: 'abc123', description: 'Single line description.' }, { _id: 101, sku: 'abc789', description: 'First line\nSecond line' }, { _id: 104, sku: 'Abc789', description: 'SKU starts with A' } ]
Match Whole Words Only
Use the \b word boundary anchor to match whole words only. A word boundary matches the position between a word character and a non-word character, or at the start or end of a string.
The following example matches documents where the description field contains the word line as a complete word, but not as part of another word like multiline:
db.products.find( { description: { $regex: /\bline\b/ } } )
[ { _id: 100, sku: 'abc123', description: 'Single line description.' }, { _id: 101, sku: 'abc789', description: 'First line\nSecond line' }, { _id: 102, sku: 'xyz456', description: 'Many spaces before line' } ]
MongoDB does not return the document with _id: 103 because its description field contains line only as part of the word Multiple\nline. The \n (newline) acts as a word boundary for the second occurrence.
참고
For matching word boundaries with UTF-8 characters, see Extend Regex Options to Match Characters Outside of ASCII.
지정된 패턴으로 시작하는 줄에 대한 여러 줄 일치 검색
다음 예시에서는 m 옵션을 사용하여 여러 줄 문자열에 대해 S 문자로 시작하는 줄을 일치시킵니다.
db.products.find( { description: { $regex: /^S/, $options: 'm' } } )
출력 예시:
[ { _id: 100, sku: 'abc123', description: 'Single line description.' }, { _id: 101, sku: 'abc789', description: 'First line\nSecond line' }, { _id: 104, sku: 'Abc789', description: 'SKU starts with A' } ]
m 옵션이 없는 경우 예시 출력은 다음과 같습니다.
[ { _id: 100, sku: 'abc123', description: 'Single line description.' }, { _id: 104, sku: 'Abc789', description: 'SKU starts with A' } ]
If the $regex pattern doesn't contain an anchor, the pattern matches against the whole string. For example:
db.products.find( { description: { $regex: /S/ } } )
출력 예시:
[ { _id: 100, sku: 'abc123', description: 'Single line description.' }, { _id: 101, sku: 'abc789', description: 'First line\nSecond line' }, { _id: 104, sku: 'Abc789', description: 'SKU starts with A' } ]
. 점 문자를 사용하여 새 줄과 일치시키기
The following example uses the s option to allow the dot character (.) to match all characters including new line, and the i option to perform a case-insensitive match:
db.products.find( { description: { $regex: /m.*line/, $options: 'si' } } )
출력 예시:
[ { _id: 102, sku: 'xyz456', description: 'Many spaces before line' }, { _id: 103, sku: 'xyz789', description: 'Multiple\nline description' } ]
Without the s option, the query returns:
[ { _id: 102, sku: 'xyz456', description: 'Many spaces before line' } ]
패턴에서 공백 무시
다음 예에서는 x 옵션을 사용하여 공백과 일치 패턴에서 # 로 표시되고 \n 로 끝나는 주석을 무시합니다.
var pattern = "abc #category code\n123 #item number" db.products.find( { sku: { $regex: pattern, $options: "x" } } )
출력 예시:
[ { _id: 100, sku: 'abc123', description: 'Single line description.' } ]
정규식을 사용하여 문자열의 대소문자 일치시키기
다음 예시에서는 표현식 "(?i)a(?-i)bc" 을(를) 사용하여 sku 필드 문자열이 포함된 항목과 일치시킵니다:
"abc""Abc"
db.products.find( { sku: { $regex: "(?i)a(?-i)bc" } } )
출력 예시:
[ { _id: 100, sku: 'abc123', description: 'Single line description.' }, { _id: 101, sku: 'abc789', description: 'First line\nSecond line' }, { _id: 104, sku: 'Abc789', description: 'SKU starts with A' } ]
정규식 옵션을 확장하여 ASCII 이외의 문자와 일치시키기
버전 6.1에 추가.
By default, some regex options (such as /b and /w) only recognize ASCII characters. This can cause unexpected results when performing regex matches against UTF-8 characters.
MongoDB 6.1부터는 UTF-8 문자와 일치하도록 *UCP 정규식 옵션을 지정할 수 있습니다.
중요
UCP 옵션의 성능
*UCP은(는) 일치를 수행하기 위해 다단계 테이블 조회가 필요하므로 *UCP 옵션을 사용하면 옵션을 지정하지 않은 경우보다 쿼리 속도가 느려집니다.
예를 들어 songs collection에 다음 문서가 있다고 가정해 보겠습니다.
db.songs.insertMany( [ { _id: 0, "artist" : "Blue Öyster Cult", "title": "The Reaper" }, { _id: 1, "artist": "Blue Öyster Cult", "title": "Godzilla" }, { _id: 2, "artist" : "Blue Oyster Cult", "title": "Take Me Away" } ] )
다음 정규식 쿼리는 정규식 일치에서 \b 옵션을 사용합니다. \b 옵션은 단어 경계와 일치합니다.
db.songs.find( { artist: { $regex: /\byster/ } } )
출력 예시:
[ { _id: 0, artist: 'Blue Öyster Cult', title: 'The Reaper' }, { _id: 1, artist: 'Blue Öyster Cult', title: 'Godzilla' } ]
The previous results are unexpected because none of the whole words in the returned artist fields begin with the matched string (yster). The Ö character in documents _id: 0 and _id: 1 is ignored when performing the match because Ö is a UTF-8 character.
The expected result is the query doesn't return any documents.
쿼리에서 UTF-8 문자를 인식할 수 있도록 하려면 패턴 앞에 *UCP 옵션을 지정하십시오.
db.songs.find( { artist: { $regex: "(*UCP)/\byster/" } } )
The previous query doesn't return any documents, which is the expected result because none of the whole words in the artist fields begin with the string yster.
팁
정규식 패턴의 이스케이프 문자
When specifying *UCP or any other regular expression option, use the correct escape characters for your shell or driver.