Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs Menu
Docs Home
/ /

MongoDB Search

이 가이드에서는 Search 빌더를 사용하여 MongoDB .NET/C# 드라이버로 $search 집계 파이프라인 단계를 빌드하는 방법에 대해 설명합니다.

$search 파이프라인 단계에 대해 자세히 알아보려면 $search를 참조하세요.

참고

Atlas for MongoDB v4.2 이상에서만 사용 가능

$search 집계 파이프라인 연산자 MongoDB 4.2 Search 인덱스 가 적용되는 MongoDB v 이상을 실행 MongoDB Atlas 클러스터에서 호스팅되는 컬렉션에만 사용할 수 있습니다. 이 연산자 의 필수 설정 및 기능에 대해 자세히 학습하려면 MongoDB 검색 설명서를 참조하세요.

이 가이드 의 예제에서는 sample_mflix 데이터베이스 의 movies 컬렉션 사용합니다. 이 컬렉션 의 문서에는 제목, 줄거리, 장르, 평점 등 영화에 대한 정보가 포함되어 있습니다. 다음 Movie 클래스는 이 컬렉션 의 문서를 모델링합니다.

[BsonIgnoreExtraElements]
public class Movie
{
[BsonId]
public ObjectId Id { get; set; }
public string Title { get; set; } = null!;
public string Plot { get; set; } = null!;
public string[] Genres { get; set; } = null!;
public int Year { get; set; }
public string Rated { get; set; } = null!;
public Imdb Imdb { get; set; } = null!;
[BsonElement("plot_embedding")]
public float[] PlotEmbedding { get; set; } = null!;
public double Score { get; set; }
[BsonElement("scoreDetails")]
[BsonIgnoreIfNull]
public SearchScoreDetails ScoreDetails { get; set; } = null!;
[BsonElement("paginationToken")]
public string PaginationToken { get; set; } = null!;
}

Movie 클래스는 각 문서 의 중첩된 imdb 필드 모델링하는 다음 Imdb 클래스를 참조합니다.

[BsonIgnoreExtraElements]
public class Imdb
{
public double Rating { get; set; }
public int Votes { get; set; }
public int Id { get; set; }
}

참고

샘플 데이터의 카멜 표기법 필드 이름

movies 컬렉션의 문서는 카멜 케이스 명명 규칙을 사용합니다. 이 가이드의 예시에서는 ConventionPack 사용하여 컬렉션의 필드를 파스칼식 대/소문자로 역직렬화하고 Movie 클래스의 속성에 매핑합니다.

사용자 지정 직렬화에 대해 자세히 알아보려면 사용자 지정 직렬화를 참조하세요.

이 가이드 의 일부 예제에서는 관련 섹션에서 소개하는 추가 컬렉션과 모델 클래스를 사용합니다. 모든 컬렉션은 Atlas 에서 제공하는 샘플 데이터 세트 에서 가져온 것입니다. 빠른 시작 을 참조하여 무료 MongoDB 클러스터 생성하고 이 샘플 데이터를 로드하는 방법을 학습하세요.

Atlas 컬렉션에서 검색 수행하려면 먼저 컬렉션에 Atlas Search 인덱스 만들어야 합니다. MongoDB 검색 인덱스는 데이터를 검색 가능한 형식으로 분류하는 데이터 구조입니다.

MongoDB Search 인덱스를 만드는 방법을 학습 MongoDB Search 인덱스 만들기 Atlas 가이드 참조하세요.

Search 클래스에는 $search 작업을 수행하는 데 사용할 수 있는 메서드가 포함되어 있습니다. 사용 가능한 $search 연산자의 전체 목록은 연산자 및 수집기 Atlas 가이드를 참조하세요.

불완전한 입력 문자열에서 일련의 문자가 포함된 단어나 구문을 검색하려면 Autocomplete() 메서드를 사용합니다.

다음 예시 string "Gravity"로 시작하는 텍스트에 대해 title 필드 에서 자동 완성 쿼리 수행합니다.

var result = moviesCollection.Aggregate()
.Search(Builders<Movie>.Search.Autocomplete(m => m.Title, "Gravity"), indexName: "movietitles")
.ToList();
...
{ "_id" : ObjectId("..."), "title" : "Gravity", "plot" : "...", "genres" : ["Drama", "Sci-Fi", "Thriller"], "year" : 2013, "rated" : "PG-13", "imdb" : { "rating" : 7.7, "votes" : "...", "id" : "..." } }
...

참고

자동 완성 쿼리를 위한 인덱싱

자동 완성 쿼리를 성공적으로 수행하려면 자동 완성을 지원하는 MongoDB 검색 인덱스를 만들어야 합니다. 자세히 학습 Atlas 설명서에서 자동 완성을 위한 필드 인덱싱 방법을 참조하세요.

MongoDB Search 인덱스 생성한 후에는 앞의 예시 와 같이 인덱스 이름을 Autocomplete() 메서드에 전달해야 합니다.

autocomplete 연산자에 대해 자세히 알아보려면 Atlas 가이드에서 autocomplete를 참조하세요.

두 개 이상의 연산자를 하나의 검색으로 결합하려면 Compound() 메서드를 사용합니다.

다음 예에서는 movies 컬렉션에서 아래의 기준과 모두 일치하는 문서를 검색합니다.

  • 문서에 imdb.rating 필드가 있음

  • rated 필드 값이 "G"이(가) 아닙니다.

  • year 필드 2000보다 큰 값이 있습니다.

var result = moviesCollection.Aggregate()
.Search(Builders<Movie>.Search.Compound()
.Must(Builders<Movie>.Search.Exists(m => m.Imdb.Rating))
.MustNot(Builders<Movie>.Search.Equals(m => m.Rated, "G"))
.Must(Builders<Movie>.Search.Range(m => m.Year, SearchRangeBuilder.Gt(2000))))
.ToList();
...
{ "_id" : ObjectId("..."), "title" : "The Dark Knight", "plot" : "...", "genres" : ["Action", "Crime", "Drama"], "year" : 2008, "rated" : "PG-13", "imdb" : { "rating" : 9.0, "votes" : "...", "id" : "..." } }
{ "_id" : ObjectId("..."), "title" : "Inception", "plot" : "...", "genres" : ["Action", "Adventure", "Sci-Fi"], "year" : 2010, "rated" : "PG-13", "imdb" : { "rating" : 8.8, "votes" : "...", "id" : "..." } }
...

compound 연산자에 대해 자세히 알아보려면 Atlas 가이드에서 compound를 참조하세요.

EmbeddedDocument() 방법을 사용하여 필드의 배열 값 내에 있는 문서에 대한 검색 작업을 수행합니다.

참고

내장된 문서에서 Atlas Search를 사용하려면 배열 필드에 embeddedDocument 인덱스를 생성해야 합니다.

embeddedDocument 인덱스를 정의하는 방법을 알아보려면 Atlas 설명서에서 embeddedDocument 유형에 대한 인덱스 정의를 참조하세요.

이 예시 sample_restaurants 데이터베이스 의 restaurants 컬렉션 사용합니다. 다음 클래스는 해당 컬렉션 의 문서를 모델링합니다.

[BsonIgnoreExtraElements]
public class Restaurant
{
[BsonId]
public ObjectId Id { get; set; }
public string Name { get; set; } = null!;
public string Cuisine { get; set; } = null!;
public string Borough { get; set; } = null!;
public List<GradeEntry> Grades { get; set; } = null!;
}
[BsonIgnoreExtraElements]
public class GradeEntry
{
public string Grade { get; set; } = null!;
public int? Score { get; set; }
}

다음 예시 해당 컬렉션 에서 grades 배열 에 grade 필드 값이 "A"인 항목이 포함된 레스토랑을 검색합니다.

var result = restaurantsCollection.Aggregate()
.Search(Builders<Restaurant>.Search.EmbeddedDocument(
r => r.Grades,
Builders<GradeEntry>.Search.Equals(g => g.Grade, "A")
), indexName: "restaurantsembedded").ToList();
...
{ "_id" : ObjectId("..."), "name" : "Riviera Caterer", "cuisine" : "American", "borough" : "Brooklyn", "grades" : [{ "grade" : "A", "score" : 5 }, { "grade" : "B", "score" : 23 }] }
...

embeddedDocument 연산자에 대해 자세히 알아보려면 Atlas 가이드에서 embeddedDocument 를 참조하세요.

필드가 지정된 값과 일치하는지 확인하려면 Equals() 메서드를 사용합니다.

다음 예시 movies 컬렉션 에서 year 필드 의 값이 2000인 문서를 검색합니다.

var result = moviesCollection.Aggregate()
.Search(Builders<Movie>.Search.Equals(m => m.Year, 2000))
.ToList();
...
{ "_id" : ObjectId("..."), "title" : "Gladiator", "plot" : "...", "genres" : ["Action", "Adventure", "Drama"], "year" : 2000, "rated" : "R", "imdb" : { "rating" : 8.5, "votes" : "...", "id" : "..." } }
{ "_id" : ObjectId("..."), "title" : "Cast Away", "plot" : "...", "genres" : ["Adventure", "Drama", "Romance"], "year" : 2000, "rated" : "PG-13", "imdb" : { "rating" : 7.8, "votes" : "...", "id" : "..." } }
...

equals 연산자에 대해 자세히 알아보려면 Atlas 가이드에서 equals를 참조하세요.

지정된 인덱스 필드 이름이 있는 문서를 검색하려면 Exists() 메서드를 사용합니다. 지정된 필드가 존재하지만 인덱스되지 않은 경우 문서는 결과 집합에 포함되지 않습니다.

다음 예시 movies 컬렉션 에서 imdb.rating 필드 존재하는 모든 문서를 검색합니다.

var result = moviesCollection.Aggregate()
.Search(Builders<Movie>.Search.Exists(m => m.Imdb.Rating))
.ToList();
...
{ "_id" : ObjectId("..."), "title" : "The Godfather", "plot" : "...", "genres" : ["Crime", "Drama"], "year" : 1972, "rated" : "R", "imdb" : { "rating" : 9.2, "votes" : "...", "id" : "..." } }
{ "_id" : ObjectId("..."), "title" : "The Shawshank Redemption", "plot" : "...", "genres" : ["Drama"], "year" : 1994, "rated" : "R", "imdb" : { "rating" : 9.3, "votes" : "...", "id" : "..." } }
...

exists 연산자에 대해 자세히 알아보려면 Atlas 가이드에서 exists를 참조하세요.

특정 도형과 관련된 문서를 검색하려면 GeoShape() 메서드를 사용합니다. 검색할 좌표를 지정할 때에는 경도를 먼저 지정하고 위도를 지정해야 합니다. 경도 값 범위는 -180 ~ 180(두 값 모두 포함)입니다. 위도 값범위는 -90 ~ 90(두 값 모두 포함)입니다.

참고

MongoDB Search는 다음을 지원 하지 않습니다.

  • 기본값이 좌표 기준계(CRS)

  • 평면형 XY 좌표계(2차원)

  • 좌표쌍 점 표기법(pointFieldName: [12, 34])

이 예시 sample_mflix 데이터베이스 의 theaters 컬렉션 사용합니다. 다음 클래스는 해당 컬렉션 의 문서를 모델링합니다.

[BsonIgnoreExtraElements]
public class Theater
{
[BsonId]
public ObjectId Id { get; set; }
public int TheaterId { get; set; }
public TheaterLocation Location { get; set; } = null!;
}
[BsonIgnoreExtraElements]
public class TheaterLocation
{
[BsonElement("geo")]
public GeoJsonPoint<GeoJson2DGeographicCoordinates> Geo { get; set; } = null!;
}

다음 예시 해당 컬렉션 에서 location.geo 필드 의 좌표가 미네소타주 미니애폴리스 지역에서 지정된 다각형 과 교차하는 모든 문서를 검색합니다.

GeoJsonPolygon<GeoJson2DGeographicCoordinates> searchArea = new(new(new(new GeoJson2DGeographicCoordinates[]
{
new(-93.5, 44.7),
new(-93.5, 45.0),
new(-93.0, 45.0),
new(-93.0, 44.7),
new(-93.5, 44.7),
})));
var result = theatersCollection.Aggregate()
.Search(Builders<Theater>.Search.GeoShape(
t => t.Location.Geo, GeoShapeRelation.Intersects, searchArea),
indexName: "theatersgeo")
.ToList();
...
{ "_id" : ObjectId("..."), "theaterId" : 1000, "location" : { "geo" : { "type" : "Point", "coordinates" : [-93.24565, 44.85466] } } }
...

geoShape 연산자에 대해 자세히 알아보려면 Atlas 가이드에서 geoShape을 참조하세요.

GeoWithin() 메서드를 사용하여 지정된 GeoJSON 필드의 좌표가 지정된 도형 내에 속하는 문서를 검색합니다. 다음 범위 내에 있는 점을 검색할 수 있습니다.

  • 경계 박스

  • 다각형

검색할 좌표를 지정할 때에는 경도를 먼저 지정하고 위도를 지정해야 합니다. 경도 값 범위는 -180 ~ 180(두 값 모두 포함)입니다. 위도 값 범위는 -90 ~ 90(두 값 모두 포함)입니다.

참고

MongoDB Search는 다음을 지원 하지 않습니다.

  • 기본값이 좌표 기준계(CRS)

  • 평면형 XY 좌표계(2차원)

  • 좌표쌍 점 표기법(pointFieldName: [12, 34])

다음 예시 theaters 컬렉션 에서 location.geo 필드 의 좌표가 지정된 다각형 내에 속하는 모든 문서를 검색합니다.

GeoJsonPolygon<GeoJson2DGeographicCoordinates> searchArea = new(new(new(new GeoJson2DGeographicCoordinates[]
{
new(-94.0, 44.5),
new(-94.0, 45.2),
new(-92.5, 45.2),
new(-92.5, 44.5),
new(-94.0, 44.5),
})));
var result = theatersCollection.Aggregate()
.Search(Builders<Theater>.Search.GeoWithin(t => t.Location.Geo, searchArea),
indexName: "theatersgeo")
.ToList();
...
{ "_id" : ObjectId("..."), "theaterId" : 1000, "location" : { "geo" : { "type" : "Point", "coordinates" : [-93.24565, 44.85466] } } }
...

geoWithin 연산자에 대해 자세히 알아보려면 Atlas 가이드에서 geoWithin을 참조하세요.

지정된 값 목록과 일치하는 필드 값이 있는 문서를 검색 하려면 In() 메서드를 사용합니다.

다음 예시 movies 컬렉션 에서 "Action" 또는 "Comedy"를 포함하는 genres 배열 있는 문서를 검색합니다.

var result = moviesCollection.Aggregate()
.Search(Builders<Movie>.Search.In(m => m.Genres, new[] { "Action", "Comedy" }))
.ToList();
...
{ "_id" : ObjectId("..."), "title" : "Home Alone", "plot" : "...", "genres" : ["Comedy", "Family"], "year" : 1990, "rated" : "PG", "imdb" : { "rating" : 7.4, "votes" : "...", "id" : "..." } }
{ "_id" : ObjectId("..."), "title" : "Die Hard", "plot" : "...", "genres" : ["Action", "Thriller"], "year" : 1988, "rated" : "R", "imdb" : { "rating" : 8.2, "votes" : "...", "id" : "..." } }
...

입력 문서와 유사한 문서를 검색하려면 MoreLikeThis() 메서드를 사용합니다.

이 예시 다음 클래스를 사용하여 검색 위한 입력 문서 지정합니다.

public class MovieSearch
{
public string Plot { get; set; } = null!;
}

다음 예시 movies 컬렉션 에서 plot 필드 의 값이 "time travel"인 객체 와 유사한 문서를 검색합니다.

var searchDocument = new MovieSearch()
{
Plot = "time travel",
};
var result = moviesCollection.Aggregate()
.Search(Builders<Movie>.Search.MoreLikeThis(searchDocument))
.ToList();
...
{ "_id" : ObjectId("..."), "title" : "Thrill Seekers", "plot" : "...", "genres" : ["Action", "Sci-Fi", "Thriller"], "year" : 1999, "rated" : "...", "imdb" : { "rating" : "...", "votes" : "...", "id" : "..." } }
{ "_id" : ObjectId("..."), "title" : "About Time", "plot" : "...", "genres" : ["Drama", "Fantasy", "Romance"], "year" : 2013, "rated" : "R", "imdb" : { "rating" : 7.8, "votes" : "...", "id" : "..." } }
...

moreLikeThis 연산자에 대해 자세히 알아보려면 Atlas 가이드에서 moreLikeThis를 참조하세요.

지정된 필드가 지정된 값에 가까운 문서를 검색하려면 Near() 메서드를 사용합니다. 다음에서 검색을 수행할 수 있습니다.

  • 숫자 필드

  • 날짜 필드

  • 지리적 점

다음 예시 movies 컬렉션 에서 imdb.rating 필드 의 값이 8.5에 가까운 문서를 검색합니다. 값이 8.5에 얼마나 가까운지에 따라 문서가 순서대로 반환됩니다.

var result = moviesCollection.Aggregate()
.Search(Builders<Movie>.Search.Near(m => m.Imdb.Rating, 8.5, 1))
.ToList();
...
{ "_id" : ObjectId("..."), "title" : "The Dark Knight", "plot" : "...", "genres" : ["Action", "Crime", "Drama"], "year" : 2008, "rated" : "PG-13", "imdb" : { "rating" : 9.0, "votes" : "...", "id" : "..." } }
{ "_id" : ObjectId("..."), "title" : "The Godfather", "plot" : "...", "genres" : ["Crime", "Drama"], "year" : 1972, "rated" : "R", "imdb" : { "rating" : 9.2, "votes" : "...", "id" : "..." } }
...

near 연산자에 대해 자세히 알아보려면 Atlas 가이드에서 near를 참조하세요.

지정된 필드에 입력 문자열이 포함된 문서를 검색하려면 Phrase() 메서드를 사용합니다.

다음 예시 movies 컬렉션 에서 plot 필드 에 "time travel" 구문이 포함된 문서를 검색합니다.

var result = moviesCollection.Aggregate()
.Search(Builders<Movie>.Search.Phrase(m => m.Plot, "time travel"))
.ToList();
...
{ "_id" : ObjectId("..."), "title" : "The Time Traveler's Wife", "plot" : "...", "genres" : ["Drama", "Fantasy", "Romance"], "year" : 2009, "rated" : "PG-13", "imdb" : { "rating" : 7.1, "votes" : "...", "id" : "..." } }
{ "_id" : ObjectId("..."), "title" : "Safety Not Guaranteed", "plot" : "...", "genres" : ["Comedy", "Drama", "Romance"], "year" : 2012, "rated" : "R", "imdb" : { "rating" : 7, "votes" : "...", "id" : "..." } }
...

컬렉션 에서 plot 필드 에 "time travel" 또는 "space adventure" 이 포함된 문서를 검색 할 수도 있습니다.

var result = moviesCollection.Aggregate()
.Search(Builders<Movie>.Search.Phrase(m => m.Plot, new List<string>() { "time travel", "space adventure" }))
.ToList();
...
{ "_id" : ObjectId("..."), "title" : "The Time Traveler's Wife", "plot" : "...", "genres" : ["Drama", "Fantasy", "Romance"], "year" : 2009, "rated" : "PG-13", "imdb" : { "rating" : 7.1, "votes" : "...", "id" : "..." } }
{ "_id" : ObjectId("..."), "title" : "Safety Not Guaranteed", "plot" : "...", "genres" : ["Comedy", "Drama", "Romance"], "year" : 2012, "rated" : "R", "imdb" : { "rating" : 7, "votes" : "...", "id" : "..." } }
...

phrase 연산자에 대해 자세히 알아보려면 Atlas 가이드에서 phrase를 참조하세요.

다음 연산자 및 구분자와 함께 문자열을 사용하여 문서를 검색하려면 QueryString() 메서드를 사용합니다.

  • AND

  • OR

  • NOT

  • ()

다음 예에서는 movies 컬렉션에서 plot 필드의 값이 다음 각 기준과 일치하는 문서를 검색합니다.

  • string "time" 또는 string "space"포함

  • 문자열을 포함하지 않음 "comedy"

var result = moviesCollection.Aggregate()
.Search(Builders<Movie>.Search.QueryString(m => m.Plot, "(time OR space) AND NOT comedy"))
.ToList();
...
{ "_id" : ObjectId("..."), "title" : "Interstellar", "plot" : "...", "genres" : ["Adventure", "Drama", "Sci-Fi"], "year" : 2014, "rated" : "PG-13", "imdb" : { "rating" : 8.7, "votes" : "...", "id" : "..." } }
{ "_id" : ObjectId("..."), "title" : "Tomorrowland", "plot" : "...", "genres" : ["Action", "Adventure", "Family"], "year" : 2015, "rated" : "PG", "imdb" : { "rating" : 6.6, "votes" : "...", "id" : "..." } }
...

queryString 연산자에 대해 자세히 알아보려면 Atlas 가이드에서 queryString을 참조하세요.

지정된 필드의 값이 지정된 숫자 또는 날짜 범위 내에 속하는 문서를 검색하려면 Range() 메서드를 사용합니다.

다음 예시 movies 컬렉션 에서 year 값이 2000 보다 크고 2010보다 작은 모든 문서를 검색합니다.

var result = moviesCollection.Aggregate()
.Search(Builders<Movie>.Search
.Range(m => m.Year, SearchRangeBuilder.Gt(2000).Lt(2010)))
.ToList();
...
{ "_id" : ObjectId("..."), "title" : "The Dark Knight", "plot" : "...", "genres" : ["Action", "Crime", "Drama"], "year" : 2008, "rated" : "PG-13", "imdb" : { "rating" : 9.0, "votes" : "...", "id" : "..." } }
{ "_id" : ObjectId("..."), "title" : "The Departed", "plot" : "...", "genres" : ["Crime", "Drama", "Thriller"], "year" : 2006, "rated" : "R", "imdb" : { "rating" : 8.5, "votes" : "...", "id" : "..." } }
...

range 연산자에 대해 자세히 알아보려면 Atlas 가이드에서 range를 참조하세요.

정규 표현식을 사용하여 문서를 검색하려면 Regex() 메서드를 사용합니다.

다음 예시 movies 컬렉션 에서 title 필드 값에 정확히 6개의 문자가 포함된 문서를 검색합니다.

var regex = "[A-Za-z]{6}";
var result = moviesCollection.Aggregate()
.Search(Builders<Movie>.Search.Regex(m => m.Title, regex,
allowAnalyzedField: true))
.ToList();
...
{ "_id" : ObjectId("..."), "title" : "Gandhi", "plot" : "...", "genres" : ["Biography", "Drama", "History"], "year" : 1982, "rated" : "PG", "imdb" : { "rating" : 8.0, "votes" : "...", "id" : "..." } }
{ "_id" : ObjectId("..."), "title" : "Batman", "plot" : "...", "genres" : ["Action", "Adventure"], "year" : 1989, "rated" : "PG-13", "imdb" : { "rating" : 7.5, "votes" : "...", "id" : "..." } }
...

참고

기본적으로 regex 연산자는 분석된 필드에서 실행할 수 없습니다. 다음과 같이 allowAnalyzedField 옵션을 true로 설정하여 분석된 필드에서 실행되도록 할 수 있습니다.

var result = moviesCollection.Aggregate()
.Search(Builders<Movie>.Search.Regex(m => m.Title, regex,
allowAnalyzedField: true))
.ToList();

allowAnalyzedField 옵션을 true로 설정하면 예기치 않은 검색 결과가 나올 수 있습니다. 자세히 알아보려면 regex 동작을 참조하세요.

regex 연산자에 대해 자세히 알아보려면 Atlas 가이드에서 regex를 참조하세요.

필드 리전 내에서 텍스트 검색 일치 항목을 검색하려면 Span() 메서드를 사용합니다. 이 메서드를 사용하면 지정된 정밀도까지 서로 가까이 있는 문자열을 찾을 수 있습니다.

참고

쿼리가 위치 정보를 추적해야 하기 때문에 span 연산자는 다른 연산자보다 계산 집약적입니다.

다음 예시 movies 컬렉션 에서 plot 필드 값이 서로 한 단어 내에 "time""travel" 문자열을 포함하는 문서를 검색합니다.

var searchTerms = new[]
{
Builders<Movie>.SearchSpan.Term(m => m.Plot, "time"),
Builders<Movie>.SearchSpan.Term(m => m.Plot, "travel")
};
var result = moviesCollection.Aggregate()
.Search(Builders<Movie>.Search.Span(Builders<Movie>.SearchSpan.Near(searchTerms, 1)))
.ToList();
...
{ "_id" : ObjectId("..."), "title" : "The Time Traveler's Wife", "plot" : "...", "genres" : ["Drama", "Fantasy", "Romance"], "year" : 2009, "rated" : "PG-13", "imdb" : { "rating" : 7.1, "votes" : "...", "id" : "..." } }
{ "_id" : ObjectId("..."), "title" : "About Time", "plot" : "...", "genres" : ["Drama", "Fantasy", "Romance"], "year" : 2013, "rated" : "R", "imdb" : { "rating" : 7.8, "votes" : "...", "id" : "..." } }
...

span 연산자에 대해 자세히 알아보려면 Atlas 가이드에서 span을 참조하세요.

Text() 메서드를 사용하여 문서 에서 지정된 문자열 또는 문자열 배열 검색 . 주어진 문자열에 여러 개의 용어가 있는 경우, MongoDB Search는 문자열의 각 텀 에 대해 개별적으로 일치하는 항목을 찾습니다.

다음 예시 movies 컬렉션 에서 plot 필드 값에 "secret agent" 문자열이 포함된 문서를 검색합니다.

var result = moviesCollection.Aggregate()
.Search(Builders<Movie>.Search.Text(m => m.Plot, "secret agent"))
.ToList();
...
{ "_id" : ObjectId("..."), "title" : "Spy Kids", "plot" : "...", "genres" : ["Action", "Adventure", "Comedy"], "year" : 2001, "rated" : "PG", "imdb" : { "rating" : 5.4, "votes" : "...", "id" : "..." } }
{ "_id" : ObjectId("..."), "title" : "The Spy Who Loved Me", "plot" : "...", "genres" : ["Action", "Adventure", "Thriller"], "year" : 1977, "rated" : "PG", "imdb" : { "rating" : 7.1, "votes" : "...", "id" : "..." } }
...

검색 문자열에 여러 용어가 포함된 경우 이 메서드는 문자열에 있는 각 용어에 대해 개별적으로 일치하는 항목도 찾습니다.

text 연산자에 대해 자세히 알아보려면 Atlas 가이드에서 text를 참조하세요.

검색 문자열에서 모든 문자와 일치할 수 있는 특수 문자를 사용하여 문서를 검색하려면 Wildcard() 메서드를 사용합니다. 검색에 사용할 수 있는 문자는 다음과 같습니다.

캐릭터
설명

?

모든 단일 문자와 일치

*

0개 이상의 문자와 일치

\

이스케이프 문자

다음 예시 title 필드 값에 string "Amer" 뒤에 다른 문자가 포함된 문서를 검색합니다.

var result = moviesCollection.Aggregate()
.Search(Builders<Movie>.Search.Wildcard(m => m.Title, "Amer*", allowAnalyzedField: true))
.ToList();
...
{ "_id" : ObjectId("..."), "title" : "American Beauty", "plot" : "...", "genres" : ["Drama"], "year" : 1999, "rated" : "R", "imdb" : { "rating" : 8.4, "votes" : "...", "id" : "..." } }
{ "_id" : ObjectId("..."), "title" : "American Gangster", "plot" : "...", "genres" : ["Biography", "Crime", "Drama"], "year" : 2007, "rated" : "R", "imdb" : { "rating" : 7.8, "votes" : "...", "id" : "..." } }
...

참고

기본적으로 wildcard 연산자는 분석된 필드에서 실행할 수 없습니다. 다음과 같이 allowAnalyzedField 옵션을 true로 설정하여 분석된 필드에서 실행되도록 할 수 있습니다.

var result = moviesCollection.Aggregate()
.Search(Builders<Movie>.Search.Wildcard(m => m.Title, "Amer*", allowAnalyzedField: true))
.ToList();

allowAnalyzedField 옵션을 true로 설정하면 예기치 않은 검색 결과가 나올 수 있습니다. 자세한 내용은 wildcard 동작을 참조하세요.

wildcard 연산자에 대해 자세히 알아보려면 Atlas 가이드에서 wildcard를 참조하세요.

돌아가기

빌더와의 운영

이 페이지의 내용