Atlas Search 빠른 시작
Atlas Search 는 MongoDB Atlas 에 내장된 전체 텍스트 검색 기능으로, 관련성 기반 앱 기능을 구축할 수 있는 원활하고 확장 가능한 환경을 제공합니다. 이 빠른 시작에서는 다음 단계에서 시작하는 방법을 설명합니다.
샘플 컬렉션 에 Atlas Search 인덱스 만듭니다.
컬렉션 을 검색 Atlas Search 쿼리 작성합니다. 다음 방법을 학습 됩니다.
기본 쿼리 실행하여 필드 에서 텀 검색
연산자 사용하여 검색 세분화
결과를 프로세스 하는 검색 옵션 추가
소요 시간: 15분
Atlas Search 인덱스 만들기
Atlas Search 인덱스 데이터를 쉽게 검색할 수 있는 형식으로 분류하는 데이터 구조입니다. 용어를 해당 용어가 포함된 문서와 매핑하여 쿼리 시점에 문서를 빠르게 검색 활성화 .
Atlas Atlas Search 사용하여 데이터를 쿼리 하려면 Atlas Atlas Search 인덱스 구성해야 합니다. 데이터를 정렬하거나 필터하다 데 정기적으로 사용하는 필드를 인덱스 것이 좋습니다.
이 섹션에서는 샘플 영화 컬렉션 에 대해 Atlas Search 인덱스 만듭니다. Atlas Search 인덱스 Atlas cluster 또는 로컬 컴퓨터에 호스팅된 배포서버 에서 만들 수 있습니다.
Atlas 클러스터를 설정합니다.
Atlas 클러스터가 아직 없다면 무료 M0 클러스터를 생성하세요. Atlas 클러스터 생성에 대한 자세한 내용은 클러스터 만들기를 참조하세요.
참고
기존 클러스터로 작업하는 경우 Atlas 프로젝트에 대해
Project Data Access Admin
이상의 액세스 권한이 있어야 합니다.새 클러스터를 생성하면 기본적으로 필요한 권한이 부여됩니다.
프로젝트당 하나의 무료
M0
클러스터만 만들 수 있습니다.이 빠른 시작에 대한 샘플 데이터 세트를 클러스터 에 아직 로드하지 않은
sample_mflix
경우 샘플 데이터베이스 클러스터 에 로드합니다.데이터 세트를 이미
sample_mflix
로드한 경우 데이터베이스sample_mflix
에 컬렉션 포함되어 있는지embedded_movies
확인합니다. 그렇지 않은sample_mflix
경우sample_mflix
데이터베이스 삭제하고 데이터 세트를 다시 로드합니다.샘플 데이터세트를 로드하는 데는 몇 분이 걸릴 수 있습니다.
왼쪽 사이드바에서 Atlas Search를 클릭합니다. Select data source 메뉴에서 클러스터 를 선택하고 Go to Atlas Search를 클릭합니다.
Atlas Search 인덱스 만듭니다.
➤ 언어 선택 드롭다운 메뉴를 사용하여 이 튜토리얼의 클라이언트 설정하다 .
샘플 데이터를 로드하면 Create Search Index를 클릭합니다.
페이지에서 다음 항목을 선택한 후 Next를 클릭합니다.
Search Type
Atlas Search 인덱스 유형을 선택합니다.
Index Name and Data Source
다음 정보를 지정합니다.
Index Name:
default
Database and Collection:
sample_mflix
movies
Configuration Method
For a guided experience, select Visual Editor.To edit the raw index definition, select JSON Editor.인덱스를 정의합니다.
다음 인덱스 정의는
movies
컬렉션 의 필드를 동적으로 인덱싱합니다.movies
컬렉션에 대한"default"
인덱스 정의를 검토합니다.인덱스 정의를 검토합니다.
인덱스 정의는 다음과 비슷해야 합니다:
{ "mappings": { "dynamic": true } } 위의 인덱스 정의는
movies
컬렉션의 각 문서에서 지원되는 유형의 필드를 동적으로 인덱싱합니다.Next를 클릭합니다.
Create Search Index를 클릭합니다.
인덱스 생성이 완료될 때까지 기다립니다.
인덱스 작성에는 약 1분 정도가 소요됩니다. 작성하는 동안 Status 열은
Build in Progress
을 읽습니다. 작성이 완료되면 Status 열에Active
이 표시됩니다.
mongosh
를 사용하여 Atlas 클러스터에 연결합니다.터미널 창에서
mongosh
를 열고 Atlas 클러스터에 연결합니다. 연결에 대한 자세한 지침은 mongosh를 통해 연결을 참조하세요.인덱스를 생성하려는 컬렉션이 포함된 데이터베이스로 전환합니다.
예시
use sample_mflix switched to db sample_mflix db.collection.createSearchIndex()
메서드를 실행하여 인덱스 만듭니다.db.movies.createSearchIndex( "default", { mappings: { dynamic: true } } ) default
MongoDB Compass 통해 Atlas cluster 에 연결합니다.
Compass 열고 Atlas cluster 에 연결합니다. 자세한 지침은 Compass 통한 연결을 참조하세요.
Atlas Search 인덱스 만듭니다.
Indexes 탭을 클릭한 다음 Search Indexes을(를) 선택합니다.
Create Index를 클릭하여 인덱스 생성 대화 상자를 엽니다.
인덱스의 이름을 지정합니다.
Atlas Search 인덱스 의 이름은 기본값 으로
default
으로 지정됩니다. 이 이름을 유지하면 해당 인덱스 연산자에 다른index
옵션을 지정하지 않는 모든 Atlas Search 쿼리 대한 기본값 검색 인덱스 됩니다. 여러 인덱스를 생성하는 경우 인덱스 전체에서 일관적인 되고 설명이 포함된 명명 규칙을 유지하는 것이 좋습니다.JSON Atlas Search 인덱스 정의를 지정합니다.
1 { 2 "analyzer": "<analyzer-for-index>", 3 "searchAnalyzer": "<analyzer-for-query>", 4 "mappings": { 5 "dynamic": <boolean>, 6 "fields": { <field-definition> } 7 }, 8 "numPartitions": <integer>, 9 "analyzers": [ <custom-analyzer> ], 10 "storedSource": <boolean> | { 11 <stored-source-definition> 12 }, 13 "synonyms": [ 14 { 15 <synonym-mapping-definition> 16 } 17 ] 18 } 19 Create Search Index를 클릭합니다.
.NET/ C# 프로젝트 설정하고 초기화합니다.
# Create a new directory and initialize the project mkdir atlas-search-quickstart && cd atlas-search-quickstart dotnet new console # Add the MongoDB .NET/C# Driver to your project dotnet add package MongoDB.Driver 더 자세한 설치 안내는 MongoDB C# 드라이버 문서를 참조하세요.
인덱스를 정의합니다.
다음 코드를
Program.cs
파일 에 붙여넣습니다.Program.cs1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 4 // connect to your Atlas deployment 5 var uri = "<connection-string>"; 6 7 var client = new MongoClient(uri); 8 9 var db = client.GetDatabase("sample_mflix"); 10 var collection = db.GetCollection<BsonDocument>("movies"); 11 12 // define your Atlas Search index 13 var index = new CreateSearchIndexModel( 14 "default", new BsonDocument 15 { 16 { "mappings", new BsonDocument 17 { 18 { "dynamic", true } 19 } 20 } 21 }); 22 23 var result = collection.SearchIndexes.CreateOne(index); 24 Console.WriteLine(result); 연결 문자열은 다음 형식을 사용해야 합니다.
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 참고
연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 연결 문자열을 찾는 방법을 자세히 알아보려면 드라이버를 통해 연결하기를 참조하세요.
연결 문자열은 다음 형식을 사용해야 합니다.
mongodb://localhost:<port-number>/?directConnection=true 인덱스를 만듭니다.
dotnet run Program.cs default
고 (Go) 모듈을 설정하고 초기화합니다.
# Create a new directory and initialize the project mkdir atlas-search-quickstart && cd atlas-search-quickstart go mod init atlas-search-quickstart # Add the MongoDB Go Driver to your project go get go.mongodb.org/mongo-driver/v2/mongo 더 자세한 설치 안내는 MongoDB Go 드라이버 문서를 참조하세요.
인덱스를 정의합니다.
다음 코드를
create-index.go
파일 에 붙여넣습니다.create-index.go1 package main 2 3 import ( 4 "context" 5 "log" 6 7 "go.mongodb.org/mongo-driver/v2/bson" 8 "go.mongodb.org/mongo-driver/v2/mongo" 9 "go.mongodb.org/mongo-driver/v2/mongo/options" 10 ) 11 12 func main() { 13 ctx := context.Background() 14 15 // Replace the placeholder with your Atlas connection string 16 const uri = "<connection-string>" 17 18 // Connect to your Atlas cluster 19 clientOptions := options.Client().ApplyURI(uri) 20 client, err := mongo.Connect(clientOptions) 21 if err != nil { 22 log.Fatalf("failed to connect to the server: %v", err) 23 } 24 defer func() { _ = client.Disconnect(ctx) }() 25 26 // Set the namespace 27 coll := client.Database("sample_mflix").Collection("movies") 28 29 // Define a simple Atlas Search index 30 indexName := "default" 31 32 // Create the default definition for search index 33 definition := bson.D{{"mappings", bson.D{{"dynamic", true}}}} 34 indexModel := mongo.SearchIndexModel{ 35 Definition: definition, 36 Options: options.SearchIndexes().SetName(indexName), 37 } 38 39 // Create the index 40 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel) 41 if err != nil { 42 log.Fatalf("failed to create the search index: %v", err) 43 } 44 log.Println("New search index named " + searchIndexName + " is building.") 45 } 연결 문자열은 다음 형식을 사용해야 합니다.
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 참고
연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 연결 문자열을 찾는 방법을 자세히 알아보려면 드라이버를 통해 연결하기를 참조하세요.
연결 문자열은 다음 형식을 사용해야 합니다.
mongodb://localhost:<port-number>/?directConnection=true 인덱스를 만듭니다.
go run create-index.go
Java 프로젝트 에 Java 운전자 버전 4.11 이상을 종속성으로 추가합니다. 패키지 관리자에 따라 다음 탭 중 하나를 선택합니다.
Maven을 사용하는 경우 프로젝트의
pom.xml
파일 에 있는dependencies
배열 에 다음 종속성을 추가합니다.pom.xml<dependencies> <!-- MongoDB Java Sync Driver v4.11.0 or later --> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>[4.11.0,)</version> </dependency> </dependencies> Gradle을 사용하는 경우 프로젝트의
build.gradle
파일 에 있는dependencies
배열 에 다음을 추가합니다.build.gradledependencies { // MongoDB Java Sync Driver v4.11.0 or later implementation 'org.mongodb:mongodb-driver-sync:[4.11.0,)' } 패키지 관리자를 실행하여 프로젝트 에 종속성을 설치합니다.
자세한 설치 지침 및 버전 호환성은 MongoDB Java 드라이버 문서를 참조하세요.
인덱스를 정의합니다.
다음 예시
CreateIndex.java
파일 에 붙여넣습니다.CreateIndex.java1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 7 public class CreateIndex { 8 public static void main(String[] args) { 9 // connect to your Atlas cluster 10 String uri = "<connection-string>"; 11 12 try (MongoClient mongoClient = MongoClients.create(uri)) { 13 // set namespace 14 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 15 MongoCollection<Document> collection = database.getCollection("movies"); 16 17 Document index = new Document("mappings", 18 new Document("dynamic", true)); 19 collection.createSearchIndex(index); 20 } 21 } 22 } 연결 문자열은 다음 형식을 사용해야 합니다.
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 참고
연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 연결 문자열을 찾는 방법을 자세히 알아보려면 드라이버를 통해 연결하기를 참조하세요.
연결 문자열은 다음 형식을 사용해야 합니다.
mongodb://localhost:<port-number>/?directConnection=true
MongoDB Kotlin 코루틴 드라이버를 설치합니다.
새 코틀린 (Kotlin) 프로젝트 생성하고 MongoDB 코틀린 (Kotlin) 코루틴 드라이버 설명서를 설치합니다.
인덱스를 정의합니다.
CreateIndex.kt
라는 파일을 만듭니다. 다음 코드를 파일에 복사하여 붙여넣습니다.CreateIndex.kt1 import com.mongodb.MongoException 2 import com.mongodb.client.model.SearchIndexModel 3 import com.mongodb.client.model.SearchIndexType 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun main() { 9 // Replace the placeholder with your MongoDB deployment's connection string 10 val uri = "<connection-string>" 11 val mongoClient = MongoClient.create(uri) 12 val database = mongoClient.getDatabase("sample_mflix") 13 val collection = database.getCollection<Document>("movies") 14 val searchIdx = Document( 15 "mappings", 16 Document("dynamic", true) 17 ) 18 runBlocking { 19 try { 20 val result = collection.createSearchIndex("default", searchIdx) 21 println("Index created: $result") 22 } catch (e: MongoException) { 23 println("Failed to create search index: ${e.message}") 24 } finally { 25 mongoClient.close() 26 } 27 } 28 } 연결 문자열은 다음 형식을 사용해야 합니다.
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 참고
연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 연결 문자열을 찾는 방법을 자세히 알아보려면 드라이버를 통해 연결하기를 참조하세요.
연결 문자열은 다음 형식을 사용해야 합니다.
mongodb://localhost:<port-number>/?directConnection=true IDE에서
CreateIndex.kt
파일 실행합니다.
Node.js 프로젝트를 초기화합니다.
# Create a new directory and initialize the project mkdir atlas-search-quickstart && cd atlas-search-quickstart npm init -y # Add the MongoDB Node.js Driver to your project npm install mongodb 자세한 설치 지침은 MongoDB 노드 드라이버 설명서를 참조하세요.
인덱스를 정의합니다.
다음 코드를
create-index.js
파일 에 붙여넣습니다.create-index.js1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async function run() { 10 try { 11 12 // set namespace 13 const database = client.db("sample_mflix"); 14 const collection = database.collection("movies"); 15 16 // define your Atlas Search index 17 const index = { 18 name: "default", 19 definition: { 20 /* search index definition fields */ 21 "mappings": { 22 "dynamic": true 23 } 24 } 25 } 26 27 // run the helper method 28 const result = await collection.createSearchIndex(index); 29 console.log(result); 30 } finally { 31 await client.close(); 32 } 33 } 34 35 run().catch(console.dir); 연결 문자열은 다음 형식을 사용해야 합니다.
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 참고
연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 연결 문자열을 찾는 방법을 자세히 알아보려면 드라이버를 통해 연결하기를 참조하세요.
연결 문자열은 다음 형식을 사용해야 합니다.
mongodb://localhost:<port-number>/?directConnection=true 인덱스를 만듭니다.
node create-index.js default
MongoDB Python 드라이버 설치합니다.
pip install pymongo 자세한 설치 지침은 MongoDB Python 드라이버 (PyMongo)를 참조하세요.
인덱스를 정의합니다.
다음 코드를
create_index.py
파일 에 붙여넣습니다.create_index.py1 from pymongo import MongoClient 2 from pymongo.operations import SearchIndexModel 3 4 # connect to your Atlas deployment 5 uri = "<connection-string>" 6 client = MongoClient(uri) 7 8 # set namespace 9 database = client["sample_mflix"] 10 collection = database["movies"] 11 12 # define your Atlas Search index 13 search_index_model = SearchIndexModel( 14 definition={ 15 "mappings": { 16 "dynamic": True 17 }, 18 }, 19 name="default", 20 ) 21 22 # create the index 23 result = collection.create_search_index(model=search_index_model) 24 print(result) 연결 문자열은 다음 형식을 사용해야 합니다.
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 참고
연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 연결 문자열을 찾는 방법을 자세히 알아보려면 드라이버를 통해 연결하기를 참조하세요.
연결 문자열은 다음 형식을 사용해야 합니다.
mongodb://localhost:<port-number>/?directConnection=true 인덱스를 만듭니다.
python create_index.py default
종속성을 설치합니다.
Homebrew 를 사용하는 경우 터미널에서 다음 명령을 실행 수 있습니다.
brew install mongodb-atlas-cli 다른 운영 체제에 대한 설치 지침은 Atlas CLI 설치를 참조하세요.
Docker설치
Docker 는 MongoDB 이미지를 가져오고 캐싱하기 위해 네트워크 연결이 필요합니다.
MacOS 또는 Window를 사용한다면 Docker Desktop v4.31 이상을 설치하세요.
Linux를 사용한다면 Docker Engine v27.0 이상을 설치하세요.
RHEL의 경우 Podman v5.0+를 사용할 수도 있습니다.
MongoDB Database Tools를 설치합니다.
샘플 데이터를 로드하는 데 사용할
mongorestore
명령에 액세스 하려면 MongoDB 명령줄 데이터베이스 도구 설치해야 합니다.
로컬 Atlas 배포를 설정합니다.
기존 Atlas 계정이 없다면 터미널에서
atlas setup
을 실행하거나 새 계정을 만드세요.atlas deployments setup
을 실행하고 메시지에 따라 로컬 배포서버 를 만듭니다. 배포서버 서버에 연결할지 묻는 메시지가 표시되면skip
을 선택합니다.자세한 지침은 로컬 Atlas 배포 생성을 참조하세요.
Atlas Search 인덱스 만듭니다.
➤ 언어 선택 드롭다운 메뉴를 사용하여 이 튜토리얼의 클라이언트 설정하다 .
샘플 데이터를 로드하면 Create Search Index를 클릭합니다.
페이지에서 다음 항목을 선택한 후 Next를 클릭합니다.
Search Type
Atlas Search 인덱스 유형을 선택합니다.
Index Name and Data Source
다음 정보를 지정합니다.
Index Name:
default
Database and Collection:
sample_mflix
movies
Configuration Method
For a guided experience, select Visual Editor.To edit the raw index definition, select JSON Editor.인덱스를 정의합니다.
다음 인덱스 정의는
movies
컬렉션 의 필드를 동적으로 인덱싱합니다.movies
컬렉션에 대한"default"
인덱스 정의를 검토합니다.인덱스 정의를 검토합니다.
인덱스 정의는 다음과 비슷해야 합니다:
{ "mappings": { "dynamic": true } } 위의 인덱스 정의는
movies
컬렉션의 각 문서에서 지원되는 유형의 필드를 동적으로 인덱싱합니다.Next를 클릭합니다.
Create Search Index를 클릭합니다.
인덱스 생성이 완료될 때까지 기다립니다.
인덱스 작성에는 약 1분 정도가 소요됩니다. 작성하는 동안 Status 열은
Build in Progress
을 읽습니다. 작성이 완료되면 Status 열에Active
이 표시됩니다.
mongosh
를 사용하여 Atlas 클러스터에 연결합니다.터미널 창에서
mongosh
를 열고 Atlas 클러스터에 연결합니다. 연결에 대한 자세한 지침은 mongosh를 통해 연결을 참조하세요.인덱스를 생성하려는 컬렉션이 포함된 데이터베이스로 전환합니다.
예시
use sample_mflix switched to db sample_mflix db.collection.createSearchIndex()
메서드를 실행하여 인덱스 만듭니다.db.movies.createSearchIndex( "default", { mappings: { dynamic: true } } ) default
MongoDB Compass 통해 Atlas cluster 에 연결합니다.
Compass 열고 Atlas cluster 에 연결합니다. 자세한 지침은 Compass 통한 연결을 참조하세요.
Atlas Search 인덱스 만듭니다.
Indexes 탭을 클릭한 다음 Search Indexes을(를) 선택합니다.
Create Index를 클릭하여 인덱스 생성 대화 상자를 엽니다.
인덱스의 이름을 지정합니다.
Atlas Search 인덱스 의 이름은 기본값 으로
default
으로 지정됩니다. 이 이름을 유지하면 해당 인덱스 연산자에 다른index
옵션을 지정하지 않는 모든 Atlas Search 쿼리 대한 기본값 검색 인덱스 됩니다. 여러 인덱스를 생성하는 경우 인덱스 전체에서 일관적인 되고 설명이 포함된 명명 규칙을 유지하는 것이 좋습니다.JSON Atlas Search 인덱스 정의를 지정합니다.
1 { 2 "analyzer": "<analyzer-for-index>", 3 "searchAnalyzer": "<analyzer-for-query>", 4 "mappings": { 5 "dynamic": <boolean>, 6 "fields": { <field-definition> } 7 }, 8 "numPartitions": <integer>, 9 "analyzers": [ <custom-analyzer> ], 10 "storedSource": <boolean> | { 11 <stored-source-definition> 12 }, 13 "synonyms": [ 14 { 15 <synonym-mapping-definition> 16 } 17 ] 18 } 19 Create Search Index를 클릭합니다.
.NET/ C# 프로젝트 설정하고 초기화합니다.
# Create a new directory and initialize the project mkdir atlas-search-quickstart && cd atlas-search-quickstart dotnet new console # Add the MongoDB .NET/C# Driver to your project dotnet add package MongoDB.Driver 더 자세한 설치 안내는 MongoDB C# 드라이버 문서를 참조하세요.
인덱스를 정의합니다.
다음 코드를
Program.cs
파일 에 붙여넣습니다.Program.cs1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 4 // connect to your Atlas deployment 5 var uri = "<connection-string>"; 6 7 var client = new MongoClient(uri); 8 9 var db = client.GetDatabase("sample_mflix"); 10 var collection = db.GetCollection<BsonDocument>("movies"); 11 12 // define your Atlas Search index 13 var index = new CreateSearchIndexModel( 14 "default", new BsonDocument 15 { 16 { "mappings", new BsonDocument 17 { 18 { "dynamic", true } 19 } 20 } 21 }); 22 23 var result = collection.SearchIndexes.CreateOne(index); 24 Console.WriteLine(result); 연결 문자열은 다음 형식을 사용해야 합니다.
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 참고
연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 연결 문자열을 찾는 방법을 자세히 알아보려면 드라이버를 통해 연결하기를 참조하세요.
연결 문자열은 다음 형식을 사용해야 합니다.
mongodb://localhost:<port-number>/?directConnection=true 인덱스를 만듭니다.
dotnet run Program.cs default
고 (Go) 모듈을 설정하고 초기화합니다.
# Create a new directory and initialize the project mkdir atlas-search-quickstart && cd atlas-search-quickstart go mod init atlas-search-quickstart # Add the MongoDB Go Driver to your project go get go.mongodb.org/mongo-driver/v2/mongo 더 자세한 설치 안내는 MongoDB Go 드라이버 문서를 참조하세요.
인덱스를 정의합니다.
다음 코드를
create-index.go
파일 에 붙여넣습니다.create-index.go1 package main 2 3 import ( 4 "context" 5 "log" 6 7 "go.mongodb.org/mongo-driver/v2/bson" 8 "go.mongodb.org/mongo-driver/v2/mongo" 9 "go.mongodb.org/mongo-driver/v2/mongo/options" 10 ) 11 12 func main() { 13 ctx := context.Background() 14 15 // Replace the placeholder with your Atlas connection string 16 const uri = "<connection-string>" 17 18 // Connect to your Atlas cluster 19 clientOptions := options.Client().ApplyURI(uri) 20 client, err := mongo.Connect(clientOptions) 21 if err != nil { 22 log.Fatalf("failed to connect to the server: %v", err) 23 } 24 defer func() { _ = client.Disconnect(ctx) }() 25 26 // Set the namespace 27 coll := client.Database("sample_mflix").Collection("movies") 28 29 // Define a simple Atlas Search index 30 indexName := "default" 31 32 // Create the default definition for search index 33 definition := bson.D{{"mappings", bson.D{{"dynamic", true}}}} 34 indexModel := mongo.SearchIndexModel{ 35 Definition: definition, 36 Options: options.SearchIndexes().SetName(indexName), 37 } 38 39 // Create the index 40 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel) 41 if err != nil { 42 log.Fatalf("failed to create the search index: %v", err) 43 } 44 log.Println("New search index named " + searchIndexName + " is building.") 45 } 연결 문자열은 다음 형식을 사용해야 합니다.
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 참고
연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 연결 문자열을 찾는 방법을 자세히 알아보려면 드라이버를 통해 연결하기를 참조하세요.
연결 문자열은 다음 형식을 사용해야 합니다.
mongodb://localhost:<port-number>/?directConnection=true 인덱스를 만듭니다.
go run create-index.go
Java 프로젝트 에 Java 운전자 버전 4.11 이상을 종속성으로 추가합니다. 패키지 관리자에 따라 다음 탭 중 하나를 선택합니다.
Maven을 사용하는 경우 프로젝트의
pom.xml
파일 에 있는dependencies
배열 에 다음 종속성을 추가합니다.pom.xml<dependencies> <!-- MongoDB Java Sync Driver v4.11.0 or later --> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>[4.11.0,)</version> </dependency> </dependencies> Gradle을 사용하는 경우 프로젝트의
build.gradle
파일 에 있는dependencies
배열 에 다음을 추가합니다.build.gradledependencies { // MongoDB Java Sync Driver v4.11.0 or later implementation 'org.mongodb:mongodb-driver-sync:[4.11.0,)' } 패키지 관리자를 실행하여 프로젝트 에 종속성을 설치합니다.
자세한 설치 지침 및 버전 호환성은 MongoDB Java 드라이버 문서를 참조하세요.
인덱스를 정의합니다.
다음 예시
CreateIndex.java
파일 에 붙여넣습니다.CreateIndex.java1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 7 public class CreateIndex { 8 public static void main(String[] args) { 9 // connect to your Atlas cluster 10 String uri = "<connection-string>"; 11 12 try (MongoClient mongoClient = MongoClients.create(uri)) { 13 // set namespace 14 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 15 MongoCollection<Document> collection = database.getCollection("movies"); 16 17 Document index = new Document("mappings", 18 new Document("dynamic", true)); 19 collection.createSearchIndex(index); 20 } 21 } 22 } 연결 문자열은 다음 형식을 사용해야 합니다.
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 참고
연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 연결 문자열을 찾는 방법을 자세히 알아보려면 드라이버를 통해 연결하기를 참조하세요.
연결 문자열은 다음 형식을 사용해야 합니다.
mongodb://localhost:<port-number>/?directConnection=true
MongoDB Kotlin 코루틴 드라이버를 설치합니다.
새 코틀린 (Kotlin) 프로젝트 생성하고 MongoDB 코틀린 (Kotlin) 코루틴 드라이버 설명서를 설치합니다.
인덱스를 정의합니다.
CreateIndex.kt
라는 파일을 만듭니다. 다음 코드를 파일에 복사하여 붙여넣습니다.CreateIndex.kt1 import com.mongodb.MongoException 2 import com.mongodb.client.model.SearchIndexModel 3 import com.mongodb.client.model.SearchIndexType 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun main() { 9 // Replace the placeholder with your MongoDB deployment's connection string 10 val uri = "<connection-string>" 11 val mongoClient = MongoClient.create(uri) 12 val database = mongoClient.getDatabase("sample_mflix") 13 val collection = database.getCollection<Document>("movies") 14 val searchIdx = Document( 15 "mappings", 16 Document("dynamic", true) 17 ) 18 runBlocking { 19 try { 20 val result = collection.createSearchIndex("default", searchIdx) 21 println("Index created: $result") 22 } catch (e: MongoException) { 23 println("Failed to create search index: ${e.message}") 24 } finally { 25 mongoClient.close() 26 } 27 } 28 } 연결 문자열은 다음 형식을 사용해야 합니다.
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 참고
연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 연결 문자열을 찾는 방법을 자세히 알아보려면 드라이버를 통해 연결하기를 참조하세요.
연결 문자열은 다음 형식을 사용해야 합니다.
mongodb://localhost:<port-number>/?directConnection=true IDE에서
CreateIndex.kt
파일 실행합니다.
Node.js 프로젝트를 초기화합니다.
# Create a new directory and initialize the project mkdir atlas-search-quickstart && cd atlas-search-quickstart npm init -y # Add the MongoDB Node.js Driver to your project npm install mongodb 자세한 설치 지침은 MongoDB 노드 드라이버 설명서를 참조하세요.
인덱스를 정의합니다.
다음 코드를
create-index.js
파일 에 붙여넣습니다.create-index.js1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async function run() { 10 try { 11 12 // set namespace 13 const database = client.db("sample_mflix"); 14 const collection = database.collection("movies"); 15 16 // define your Atlas Search index 17 const index = { 18 name: "default", 19 definition: { 20 /* search index definition fields */ 21 "mappings": { 22 "dynamic": true 23 } 24 } 25 } 26 27 // run the helper method 28 const result = await collection.createSearchIndex(index); 29 console.log(result); 30 } finally { 31 await client.close(); 32 } 33 } 34 35 run().catch(console.dir); 연결 문자열은 다음 형식을 사용해야 합니다.
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 참고
연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 연결 문자열을 찾는 방법을 자세히 알아보려면 드라이버를 통해 연결하기를 참조하세요.
연결 문자열은 다음 형식을 사용해야 합니다.
mongodb://localhost:<port-number>/?directConnection=true 인덱스를 만듭니다.
node create-index.js default
MongoDB Python 드라이버 설치합니다.
pip install pymongo 자세한 설치 지침은 MongoDB Python 드라이버 (PyMongo)를 참조하세요.
인덱스를 정의합니다.
다음 코드를
create_index.py
파일 에 붙여넣습니다.create_index.py1 from pymongo import MongoClient 2 from pymongo.operations import SearchIndexModel 3 4 # connect to your Atlas deployment 5 uri = "<connection-string>" 6 client = MongoClient(uri) 7 8 # set namespace 9 database = client["sample_mflix"] 10 collection = database["movies"] 11 12 # define your Atlas Search index 13 search_index_model = SearchIndexModel( 14 definition={ 15 "mappings": { 16 "dynamic": True 17 }, 18 }, 19 name="default", 20 ) 21 22 # create the index 23 result = collection.create_search_index(model=search_index_model) 24 print(result) 연결 문자열은 다음 형식을 사용해야 합니다.
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 참고
연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 연결 문자열을 찾는 방법을 자세히 알아보려면 드라이버를 통해 연결하기를 참조하세요.
연결 문자열은 다음 형식을 사용해야 합니다.
mongodb://localhost:<port-number>/?directConnection=true 인덱스를 만듭니다.
python create_index.py default
Atlas Search 쿼리 작성
Atlas Search 쿼리는 집계 파이프라인 단계의 형태를 취합니다. Atlas Search 주로 쿼리 파이프라인의 첫 번째 단계인 $search
단계와 함께 사용합니다. 이 단계를 파이프라인의 다른 단계와 함께 사용할 수도 있습니다.
Atlas Search 쿼리 실행 Atlas Search 검색 인덱스 사용하여 컬렉션 에서 관련 데이터를 찾고 조회 . 또한 Atlas Search 검색 결과를 더욱 구체화하는 $searchMeta
데 사용할 수 있는 단계, 여러 하위 파이프라인, 여러 쿼리 연산자 및 수집기를 제공합니다.
이 섹션에서는 인덱싱된 컬렉션 에 대해 쿼리를 실행 .
기본 쿼리 실행합니다.
텍스트 연산자 사용하여 기본 $search
쿼리 실행합니다.
이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
plot
필드baseball
라는 단어가 포함되어야 합니다.
다음 쿼리 Query Editor에 붙여넣은 다음 Query Editor에서 Search 버튼을 클릭합니다.
1 [ 2 { 3 $search: 4 { 5 text: { 6 query: "baseball", 7 path: "plot" 8 } 9 } 10 } 11 ]
SCORE: 3.8531038761138916 _id: "573a13b3f29313caabd3b409" fullplot: "Three guys, all their lives, have been living in the shadow of bullies…" imdb: Object year: 2006 ... SCORE: 3.6254453659057617 _id: "573a1399f29313caabcee801" plot: "A young boy is bequeathed the ownership of a professional baseball tea..." genres: Array runtime: 119 ... SCORE: 3.6254453659057617 _id: "573a139af29313caabcefe18" plot: "A trained chimpanzee plays third base for a minor-league baseball team..." genres: Array runtime: 94 ... ...
참고
Search Tester는 반환하는 문서의 모든 필드를 표시하지 않을 수 있습니다. 쿼리 경로에 지정한 필드를 비롯하여 모든 필드를 보려면 결과에서 문서를 펼칩니다.
검색 를 좁힙니다.
Atlas Search 복잡한 쿼리를 빌드 하고 사용 사례 에 맞는 보다 구체적인 결과를 조회 사용할 수 있는 여러 연산자 를 제공합니다. 복합 연산자 사용하여 여러 연산자를 단일 쿼리 로 결합하도록 $search
쿼리 업데이트합니다.
이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
plot
필드baseball
라는 단어가 포함되어야 합니다.genres
필드에는Comedy
또는Romance
가 포함되어서는 안 됩니다.
다음 쿼리 Query Editor에 붙여넣은 다음 Query Editor에서 Search 버튼을 클릭합니다.
1 [ 2 { 3 "$search": { 4 "compound": { 5 "must": [ 6 { 7 "text": { 8 "query": "baseball", 9 "path": "plot" 10 } 11 } 12 ], 13 "mustNot": [ 14 { 15 "text": { 16 "query": ["Comedy", "Romance"], 17 "path": "genres" 18 } 19 } 20 ] 21 } 22 } 23 } 24 ]
SCORE: 3.4706974029541016 _id: "573a1393f29313caabcdca79" title: "The Pride of the Yankees" plot: "The story of the life and career of the famed baseball player, Lou Geh…" genres: ["Biography", "Drama", "Family"] ... SCORE: 3.4706974029541016 _id: "573a1399f29313caabcecef1" title: "The Babe" plot: "Babe Ruth becomes a baseball legend but is unheroic to those who know …" genres: ["Biography", "Drama", "Sport"] ... SCORE: 3.406810760498047 _id: "573a13bdf29313caabd5813d" title: "Sugar" plot: "Dominican baseball star Miguel \"Sugar\" Santos is recruited to play in …" genres: ["Drama", "Sport"] ... ...
결과를 처리합니다.
Atlas Search Atlas Search 쿼리 결과를 추가로 프로세스 데 사용할 수 있는 여러 검색 옵션을 제공합니다. 쿼리 에 정렬 옵션을 추가하여 결과를 특정 순서로 표시합니다.
이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
plot
필드baseball
라는 단어가 포함되어야 합니다.genres
필드에는Comedy
또는Romance
가 포함되어서는 안 됩니다.released
날짜 필드 기준으로 결과를 내림차순으로 정렬합니다. Atlas Search 가장 최근 영화를 먼저 반환합니다.
다음 쿼리를 복사하여 Query Editor에 붙여 넣은 다음 Query Editor에서 Search 버튼을 클릭합니다.
1 [ 2 { 3 "$search": { 4 "compound": { 5 "must": [ 6 { 7 "text": { 8 "query": "baseball", 9 "path": "plot" 10 } 11 } 12 ], 13 "mustNot": [ 14 { 15 "text": { 16 "query": ["Comedy", "Romance"], 17 "path": "genres" 18 } 19 } 20 ] 21 }, 22 "sort": { 23 "released": -1 24 } 25 } 26 } 27 ]
SCORE: 3.173170804977417 _id: "573a13ccf29313caabd832f5" plot: "A sports agent stages an unconventional recruitment strategy to get ta…" title: "Million Dollar Arm" genres: Array (3) released: 2014-05-16T00:00:00.000+00:00 ... SCORE: 3.2858426570892334 _id: "573a13d9f29313caabda97d8" plot: "A Taiwanese high school baseball team travels to Japan in 1931 to comp…" title: "Kano" genres: Array (3) released: 2014-02-27T00:00:00.000+00:00 ... SCORE: 2.4570295810699463 _id: "573a13daf29313caabdad92d" plot: "12-year-old Josh is a mixed race boy and a promising baseball player..." title: "Calloused Hands" genres: Array (1) released: 2013-03-03T00:00:00.000+00:00 ... ...
기본 쿼리 실행합니다.
텍스트 연산자 사용하여 기본 $search
쿼리 실행합니다.
이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
1 db.movies.aggregate([ 2 { 3 $search: 4 { 5 "text": { 6 "query": "baseball", 7 "path": "plot" 8 } 9 } 10 }, 11 { 12 $limit: 3 13 }, 14 { 15 $project: { 16 "_id": 0, 17 "title": 1, 18 "plot": 1 19 } 20 } 21 ])
{ "plot" : "A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.", "title" : "The Benchwarmers" } { "plot" : "A young boy is bequeathed the ownership of a professional baseball team.", "title" : "Little Big League" } { "plot" : "A trained chimpanzee plays third base for a minor-league baseball team.", "title" : "Ed" }
검색 를 좁힙니다.
Atlas Search 복잡한 쿼리를 빌드 하고 사용 사례 에 맞는 보다 구체적인 결과를 조회 사용할 수 있는 여러 연산자 를 제공합니다. 복합 연산자 사용하여 여러 연산자를 단일 쿼리 로 결합하도록 $search
쿼리 업데이트합니다.
이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
plot
필드baseball
라는 단어가 포함되어야 합니다.genres
필드에는Comedy
또는Romance
가 포함되어서는 안 됩니다.
1 db.movies.aggregate([ 2 { 3 $search: { 4 "compound": { 5 "must": [ 6 { 7 "text": { 8 "query": "baseball", 9 "path": "plot" 10 } 11 } 12 ], 13 "mustNot": [ 14 { 15 "text": { 16 "query": ["Comedy", "Romance"], 17 "path": "genres" 18 } 19 } 20 ] 21 } 22 } 23 }, 24 { 25 $limit: 3 26 }, 27 { 28 $project: { 29 "_id": 0, 30 "title": 1, 31 "plot": 1, 32 "genres": 1 33 } 34 } 35 ])
[ { plot: 'The story of the life and career of the famed baseball player, Lou Gehrig.', genres: [ 'Biography', 'Drama', 'Family' ], title: 'The Pride of the Yankees' }, { plot: 'Babe Ruth becomes a baseball legend but is unheroic to those who know him.', genres: [ 'Biography', 'Drama', 'Sport' ], title: 'The Babe' }, { plot: 'Dominican baseball star Miguel "Sugar" Santos is recruited to play in the U.S. minor-leagues.', genres: [ 'Drama', 'Sport' ], title: 'Sugar' } ]
결과를 처리합니다.
Atlas Search Atlas Search 쿼리 결과를 추가로 프로세스 데 사용할 수 있는 여러 검색 옵션을 제공합니다. 쿼리 에 정렬 옵션을 추가하여 결과를 특정 순서로 표시합니다.
이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
plot
필드baseball
라는 단어가 포함되어야 합니다.genres
필드에는Comedy
또는Romance
가 포함되어서는 안 됩니다.released
날짜 필드 기준으로 결과를 내림차순으로 정렬합니다. Atlas Search 가장 최근 영화를 먼저 반환합니다.$limit 및 $ 프로젝트 단계는 3 문서와
title
,plot
,genres
및released
필드만 반환합니다.
1 db.movies.aggregate([ 2 { 3 $search: { 4 "compound": { 5 "must": [ { 6 "text": { 7 "query": "baseball", 8 "path": "plot" 9 } 10 }], 11 "mustNot": [ { 12 "text": { 13 "query": ["Comedy", "Romance"], 14 "path": "genres" 15 } 16 } ] 17 }, 18 "sort": { 19 "released": -1 20 } 21 } 22 }, 23 { 24 $limit: 3 25 }, 26 { 27 $project: { 28 "_id": 0, 29 "title": 1, 30 "plot": 1, 31 "genres": 1, 32 "released": 1 33 } 34 } 35 ])
[ { plot: 'A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.', genres: [ 'Biography', 'Drama', 'Sport' ], title: 'Million Dollar Arm', released: ISODate('2014-05-16T00:00:00.000Z') }, { plot: 'A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.', genres: [ 'Biography', 'Drama', 'History' ], title: 'Kano', released: ISODate('2014-02-27T00:00:00.000Z') }, { plot: "12-year-old Josh is a mixed race boy and a promising baseball player...", genres: [ 'Drama' ], title: 'Calloused Hands', released: ISODate('2013-03-03T00:00:00.000Z') } ]
기본 쿼리 실행합니다.
텍스트 연산자 사용하여 기본 $search
쿼리 실행합니다.
MongoDB Compass에서 이 쿼리를 실행하려면 다음 안내를 따르세요.
Aggregations 탭을 클릭합니다.
Select...를 클릭한 다음 드롭다운에서 단계를 선택하고 해당 단계에 대한 쿼리를 추가하여 다음 파이프라인 단계를 각각 구성합니다. 단계를 추가하려면 Add Stage을 클릭합니다.
이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
파이프라인 단계쿼리$search
{ "text": { "query": "baseball", "path": "plot" } } $limit
3 $project
{ "_id": 0, "title": 1, "plot": 1, }
Auto Preview를 활성화한 경우 MongoDB Compass는 $project
파이프라인 단계 옆에 다음 문서를 표시합니다.
{ "plot" : "A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.", "title" : "The Benchwarmers" } { "plot" : "A young boy is bequeathed the ownership of a professional baseball team.", "title" : "Little Big League" } { "plot" : "A trained chimpanzee plays third base for a minor-league baseball team.", "title" : "Ed" }
검색 를 좁힙니다.
Atlas Search 복잡한 쿼리를 빌드 하고 사용 사례 에 맞는 보다 구체적인 결과를 조회 사용할 수 있는 여러 연산자 를 제공합니다. 복합 연산자 사용하여 여러 연산자를 단일 쿼리 로 결합하도록 $search
쿼리 업데이트합니다.
이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
plot
필드baseball
라는 단어가 포함되어야 합니다.genres
필드에는Comedy
또는Romance
가 포함되어서는 안 됩니다.
MongoDB Compass 에서 다음 파이프라인 단계를 업데이트합니다.
파이프라인 단계 | 쿼리 | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
| ||||||||||||||||||||
|
|
Auto Preview를 활성화한 경우 MongoDB Compass는 $project
파이프라인 단계 옆에 다음 문서를 표시합니다.
{ "plot" : "The story of the life and career of the famed baseball player, Lou Gehrig.", "genres" : [ "Biography", "Drama", "Family" ], "title" : "The Pride of the Yankees" } { "plot" : "Babe Ruth becomes a baseball legend but is unheroic to those who know him.", "genres" : [ "Biography", "Drama", "Sport" ], "title" : "The Babe" } { "plot" : "Dominican baseball star Miguel \"Sugar\" Santos is recruited to play in the U.S. minor-leagues.", "genres" : [ "Drama", "Sport" ], "title" : "Sugar" }
결과를 처리합니다.
Atlas Search Atlas Search 쿼리 결과를 추가로 프로세스 데 사용할 수 있는 여러 검색 옵션을 제공합니다. 쿼리 에 정렬 옵션을 추가하여 결과를 특정 순서로 표시합니다.
이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
plot
필드baseball
라는 단어가 포함되어야 합니다.genres
필드에는Comedy
또는Romance
가 포함되어서는 안 됩니다.released
날짜 필드 기준으로 결과를 내림차순으로 정렬합니다. Atlas Search 가장 최근 영화를 먼저 반환합니다.$limit 및 $ 프로젝트 단계는 3 문서와
title
,plot
,genres
및released
필드만 반환합니다.
MongoDB Compass 에서 다음 파이프라인 단계를 업데이트합니다.
파이프라인 단계 | 쿼리 | |||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
| |||||||||||||||||||||||
|
|
Auto Preview를 활성화한 경우 MongoDB Compass는 $project
파이프라인 단계 옆에 다음 문서를 표시합니다.
[ { plot: 'A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.', genres: [ 'Biography', 'Drama', 'Sport' ], title: 'Million Dollar Arm', released: 2014-05-16T00:00:00.000+00:00 }, { plot: 'A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.', genres: [ 'Biography', 'Drama', 'History' ], title: 'Kano', released: 2014-02-27T00:00:00.000+00:00 }, { plot: "12-year-old Josh is a mixed race boy and a promising baseball player...", genres: [ 'Drama' ], title: 'Calloused Hands', released: 2013-03-03T00:00:00.000+00:00 } ]
기본 쿼리 실행합니다.
텍스트 연산자 사용하여 기본 $search
쿼리 실행합니다.
Program.cs
파일의 내용을 다음 코드로 바꿉니다.이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class BasicQuery 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 // define and run pipeline 23 var results = moviesCollection.Aggregate() 24 .Search(Builders<MovieDocument>.Search.Text(movie => movie.Plot, "baseball")) 25 .Project<MovieDocument>(Builders<MovieDocument>.Projection 26 .Include(movie => movie.Plot) 27 .Include(movie => movie.Title) 28 .Exclude(movie => movie.Id)) 29 .Limit(3) 30 .ToList(); 31 32 // print results 33 foreach (var movie in results) 34 { 35 Console.WriteLine(movie.ToJson()); 36 } 37 } 38 } 39 40 [ ]41 public class MovieDocument 42 { 43 [ ]44 public ObjectId Id { get; set; } 45 public string Plot { get; set; } 46 public string Title { get; set; } 47 } <connection-string>
을(를) 지정한 다음 쿼리 실행 .dotnet run Program.cs { "plot" : "A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.", "title" : "The Benchwarmers" } { "plot" : "A young boy is bequeathed the ownership of a professional baseball team.", "title" : "Little Big League" } { "plot" : "A trained chimpanzee plays third base for a minor-league baseball team.", "title" : "Ed" }
검색 를 좁힙니다.
Atlas Search 복잡한 쿼리를 빌드 하고 사용 사례 에 맞는 보다 구체적인 결과를 조회 사용할 수 있는 여러 연산자 를 제공합니다. 복합 연산자 사용하여 여러 연산자를 단일 쿼리 로 결합하도록 $search
쿼리 업데이트합니다.
다음 코드를 사용하여
Program.cs
파일 수정합니다.이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
plot
필드baseball
라는 단어가 포함되어야 합니다.genres
필드에는Comedy
또는Romance
가 포함되어서는 안 됩니다.
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class CompoundQuery 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 // declare data for the compound query 23 string[] genres = { "Comedy", "Romance" }; 24 25 // define and run pipeline 26 var results = moviesCollection.Aggregate() 27 .Search(Builders<MovieDocument>.Search.Compound() 28 .Must(Builders<MovieDocument>.Search.Text(movie => movie.Plot, "baseball")) 29 .MustNot((Builders<MovieDocument>.Search.Text(movie => movie.Genres, genres)))) 30 .Project<MovieDocument>(Builders<MovieDocument>.Projection 31 .Exclude(movie => movie.Id) 32 .Include(movie => movie.Plot) 33 .Include(movie => movie.Title) 34 .Include(movie => movie.Genres)) 35 .Limit(3) 36 .ToList(); 37 38 // print results 39 foreach (var movie in results) 40 { 41 Console.WriteLine(movie.ToJson()); 42 } 43 } 44 } 45 46 [ ]47 public class MovieDocument 48 { 49 [ ]50 public ObjectId Id { get; set; } 51 public string Plot { get; set; } 52 public string Title { get; set; } 53 public string[] Genres { get; set; } 54 } <connection-string>
을(를) 지정한 다음 쿼리 실행 .dotnet run Program.cs { "plot" : "The story of the life and career of the famed baseball player, Lou Gehrig.", "title" : "The Pride of the Yankees", "genres" : ["Biography", "Drama", "Family"] } { "plot" : "Babe Ruth becomes a baseball legend but is unheroic to those who know him.", "title" : "The Babe", "genres" : ["Biography", "Drama", "Sport"] } { "plot" : "Dominican baseball star Miguel \"Sugar\" Santos is recruited to play in the U.S. minor-leagues.", "title" : "Sugar", "genres" : ["Drama", "Sport"] }
결과를 처리합니다.
Atlas Search Atlas Search 쿼리 결과를 추가로 프로세스 데 사용할 수 있는 여러 검색 옵션을 제공합니다. 쿼리 에 정렬 옵션을 추가하여 결과를 특정 순서로 표시합니다.
다음 코드를 사용하여
Program.cs
파일 수정합니다.이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
plot
필드baseball
라는 단어가 포함되어야 합니다.genres
필드에는Comedy
또는Romance
가 포함되어서는 안 됩니다.released
날짜 필드 기준으로 결과를 내림차순으로 정렬합니다. Atlas Search 가장 최근 영화를 먼저 반환합니다.$limit 및 $ 프로젝트 단계는 3 문서와
title
,plot
,genres
및released
필드만 반환합니다.
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class SortQuery 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 // declare data for the compound query 23 string[] genres = { "Comedy", "Romance" }; 24 25 // define search options 26 var searchOptions = new SearchOptions<MovieDocument>() 27 { 28 Sort = Builders<MovieDocument>.Sort.Descending(movie => movie.Released), 29 }; 30 31 // define and run pipeline 32 var results = moviesCollection.Aggregate() 33 .Search(Builders<MovieDocument>.Search.Compound() 34 .Must(Builders<MovieDocument>.Search.Text(movie => movie.Plot, "baseball")) 35 .MustNot((Builders<MovieDocument>.Search.Text(movie => movie.Genres, genres))), searchOptions) 36 .Project<MovieDocument>(Builders<MovieDocument>.Projection 37 .Exclude(movie => movie.Id) 38 .Include(movie => movie.Plot) 39 .Include(movie => movie.Title) 40 .Include(movie => movie.Genres) 41 .Include(movie => movie.Released)) 42 .Limit(3) 43 .ToList(); 44 45 // print results 46 foreach (var movie in results) 47 { 48 Console.WriteLine(movie.ToJson()); 49 } 50 } 51 } 52 53 [ ]54 public class MovieDocument 55 { 56 [ ]57 public ObjectId Id { get; set; } 58 public string Plot { get; set; } 59 public string Title { get; set; } 60 public string[] Genres { get; set; } 61 public DateTime Released { get; set; } 62 } <connection-string>
을(를) 지정한 다음 쿼리 실행 .dotnet run Program.cs { "plot" : "A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.", "title" : "Million Dollar Arm", "genres" : ["Biography", "Drama", "Sport"], "released" : { "$date" : "2014-05-16T00:00:00Z" } } { "plot" : "A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.", "title" : "Kano", "genres" : ["Biography", "Drama", "History"], "released" : { "$date" : "2014-02-27T00:00:00Z" } } { "plot" : "12-year-old Josh is a mixed race boy and a promising baseball player. He is abused by his mother's boyfriend Byrd, and neglected by his mother Debbie. He forges his own path in life when ...", "title" : "Calloused Hands", "genres" : ["Drama"], "released" : { "$date" : "2013-03-03T00:00:00Z" } }
기본 쿼리 실행합니다.
텍스트 연산자 사용하여 기본 $search
쿼리 실행합니다.
run-query.go
(이)라는 새 파일 만들고 다음 코드를 붙여넣습니다.이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "go.mongodb.org/mongo-driver/v2/bson" 9 "go.mongodb.org/mongo-driver/v2/mongo" 10 "go.mongodb.org/mongo-driver/v2/mongo/options" 11 ) 12 13 func main() { 14 var err error 15 // connect to the Atlas cluster 16 ctx := context.Background() 17 client, err := mongo.Connect(options.Client().SetTimeout(5 * time.Second).ApplyURI("<connection-string>")) 18 if err != nil { 19 panic(err) 20 } 21 defer client.Disconnect(ctx) 22 // set namespace 23 collection := client.Database("sample_mflix").Collection("movies") 24 // define pipeline 25 searchStage := bson.D{{"$search", bson.D{ 26 {"text", bson.D{ 27 {"path", "plot"}, 28 {"query", "baseball"}, 29 }}, 30 }}} 31 limitStage := bson.D{{"$limit", 3}} 32 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"plot", 1}, {"_id", 0}}}} 33 // run pipeline 34 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}) 35 if err != nil { 36 panic(err) 37 } 38 // print results 39 var results []bson.D 40 if err = cursor.All(context.TODO(), &results); err != nil { 41 panic(err) 42 } 43 for _, result := range results { 44 fmt.Println(result) 45 } 46 } <connection-string>
을(를) 지정한 다음 쿼리 실행 .go run run-query.go {"plot":"A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.","title":"The Benchwarmers"} {"plot":"A young boy is bequeathed the ownership of a professional baseball team.","title":"Little Big League"} {"plot":"A trained chimpanzee plays third base for a minor-league baseball team.","title":"Ed"}
검색 를 좁힙니다.
Atlas Search 복잡한 쿼리를 빌드 하고 사용 사례 에 맞는 보다 구체적인 결과를 조회 사용할 수 있는 여러 연산자 를 제공합니다. 복합 연산자 사용하여 여러 연산자를 단일 쿼리 로 결합하도록 $search
쿼리 업데이트합니다.
복합 쿼리 사용하도록
run-query.go
을(를) 수정합니다.이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
plot
필드baseball
라는 단어가 포함되어야 합니다.genres
필드에는Comedy
또는Romance
가 포함되어서는 안 됩니다.
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "go.mongodb.org/mongo-driver/v2/bson" 9 "go.mongodb.org/mongo-driver/v2/mongo" 10 "go.mongodb.org/mongo-driver/v2/mongo/options" 11 ) 12 13 func main() { 14 var err error 15 // connect to the Atlas cluster 16 ctx := context.Background() 17 client, err := mongo.Connect(options.Client().SetTimeout(5 * time.Second).ApplyURI("<connection-string>")) 18 if err != nil { 19 panic(err) 20 } 21 defer client.Disconnect(ctx) 22 // set namespace 23 collection := client.Database("sample_mflix").Collection("movies") 24 // define pipeline 25 searchStage := bson.D{{"$search", bson.M{ 26 "compound": bson.M{ 27 "must": bson.A{ 28 bson.M{ 29 "text": bson.D{ 30 {"path", "plot"}, {"query", "baseball"}, 31 }, 32 }, 33 }, 34 "mustNot": bson.A{ 35 bson.M{ 36 "text": bson.M{ 37 "path": "genres", "query": []string{"Comedy", "Romance"}, 38 }, 39 }, 40 }, 41 }, 42 }}} 43 limitStage := bson.D{{"$limit", 3}} 44 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"plot", 1}, {"genres", 1}, {"_id", 0}}}} 45 // run pipeline 46 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}) 47 if err != nil { 48 panic(err) 49 } 50 // print results 51 var results []bson.D 52 if err = cursor.All(context.TODO(), &results); err != nil { 53 panic(err) 54 } 55 for _, result := range results { 56 fmt.Println(result) 57 } 58 } <connection-string>
을(를) 지정한 다음 쿼리 실행 .go run run-query.go {"plot":"The story of the life and career of the famed baseball player, Lou Gehrig.","genres":["Biography","Drama","Family"],"title":"The Pride of the Yankees"} {"plot":"Babe Ruth becomes a baseball legend but is unheroic to those who know him.","genres":["Biography","Drama","Sport"],"title":"The Babe"} {"plot":"Dominican baseball star Miguel \"Sugar\" Santos is recruited to play in the U.S. minor-leagues.","genres":["Drama","Sport"],"title":"Sugar"}
결과를 처리합니다.
Atlas Search Atlas Search 쿼리 결과를 추가로 프로세스 데 사용할 수 있는 여러 검색 옵션을 제공합니다. 쿼리 에 정렬 옵션을 추가하여 결과를 특정 순서로 표시합니다.
run-query.go
를 수정하여 정렬 옵션을 추가합니다.이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
plot
필드baseball
라는 단어가 포함되어야 합니다.genres
필드에는Comedy
또는Romance
가 포함되어서는 안 됩니다.released
날짜 필드 기준으로 결과를 내림차순으로 정렬합니다. Atlas Search 가장 최근 영화를 먼저 반환합니다.$limit 및 $ 프로젝트 단계는 3 문서와
title
,plot
,genres
및released
필드만 반환합니다.
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "go.mongodb.org/mongo-driver/v2/bson" 9 "go.mongodb.org/mongo-driver/v2/mongo" 10 "go.mongodb.org/mongo-driver/v2/mongo/options" 11 ) 12 13 func main() { 14 var err error 15 // connect to the Atlas cluster 16 ctx := context.Background() 17 client, err := mongo.Connect(options.Client().SetTimeout(5 * time.Second).ApplyURI("<connection-string>")) 18 if err != nil { 19 panic(err) 20 } 21 defer client.Disconnect(ctx) 22 // set namespace 23 collection := client.Database("sample_mflix").Collection("movies") 24 // define pipeline 25 searchStage := bson.D{{"$search", bson.M{ 26 "compound": bson.M{ 27 "must": bson.A{ 28 bson.M{ 29 "text": bson.D{ 30 {"path", "plot"}, {"query", "baseball"}, 31 }, 32 }, 33 }, 34 "mustNot": bson.A{ 35 bson.M{ 36 "text": bson.M{ 37 "path": "genres", "query": []string{"Comedy", "Romance"}, 38 }, 39 }, 40 }, 41 }, 42 "sort": bson.D{ 43 {"released", -1}, 44 }, 45 }}} 46 limitStage := bson.D{{"$limit", 3}} 47 projectStage := bson.D{{"$project", bson.D{{"_id", 0}, {"title", 1}, {"plot", 1}, {"genres", 1}, {"released", 1}}}} 48 // run pipeline 49 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}) 50 if err != nil { 51 panic(err) 52 } 53 // print results 54 var results []bson.D 55 if err = cursor.All(context.TODO(), &results); err != nil { 56 panic(err) 57 } 58 for _, result := range results { 59 fmt.Println(result) 60 } 61 } <connection-string>
을(를) 지정한 다음 쿼리 실행 .go run run-query.go {"plot":"A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.","genres":["Biography","Drama","Sport"],"title":"Million Dollar Arm","released":{"$date":{"$numberLong":"1400198400000"}}} {"plot":"A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.","genres":["Biography","Drama","History"],"title":"Kano","released":{"$date":{"$numberLong":"1393459200000"}}} {"plot":"12-year-old Josh is a mixed race boy and a promising baseball player. He is abused by his mother's boyfriend Byrd, and neglected by his mother Debbie. He forges his own path in life when ...","genres":["Drama"],"title":"Calloused Hands","released":{"$date":{"$numberLong":"1362268800000"}}}
종속성을 설치합니다.
CLASSPATH
에 다음 라이브러리가 포함되어 있는지 확인합니다.
| 4.11.0 또는 그 이상의 버전 |
| 4.11.0 또는 그 이상의 버전 |
| 1.7.30 또는 그 이상의 버전 |
자세한 설치 지침 및 버전 호환성은 MongoDB Java 드라이버 문서를 참조하세요.
기본 쿼리 실행합니다.
텍스트 연산자 사용하여 기본 $search
쿼리 실행합니다.
RunQuery.java
(이)라는 새 파일 만들고 다음 코드를 붙여넣습니다.이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
1 import java.util.Arrays; 2 import java.util.List; 3 import static com.mongodb.client.model.Aggregates.limit; 4 import static com.mongodb.client.model.Aggregates.project; 5 import static com.mongodb.client.model.Projections.excludeId; 6 import static com.mongodb.client.model.Projections.fields; 7 import static com.mongodb.client.model.Projections.include; 8 import com.mongodb.client.MongoClient; 9 import com.mongodb.client.MongoClients; 10 import com.mongodb.client.MongoCollection; 11 import com.mongodb.client.MongoDatabase; 12 import org.bson.Document; 13 14 public class RunQuery { 15 public static void main( String[] args ) { 16 String uri = "<connection-string>"; 17 18 try (MongoClient mongoClient = MongoClients.create(uri)) { 19 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 20 MongoCollection<Document> collection = database.getCollection("movies"); 21 22 Document textQuery = new Document("query", "baseball").append("path","plot"); 23 24 Document searchStage = new Document("$search", 25 new Document("index", "default") 26 .append("text", textQuery)); 27 28 collection.aggregate(Arrays.asList( 29 searchStage, 30 limit(3), 31 project(fields(excludeId(), include("title", "plot")))) 32 ).forEach(doc -> System.out.println(doc.toJson())); 33 } 34 } 35 } 참고
Maven 환경에서 샘플 코드를 실행하려면 파일의 가져오기 문 위에 다음을 추가하세요.
package com.mongodb.drivers; <connection-string>
을(를) 지정한 다음 쿼리 실행 .javac RunQuery.java java RunQuery {"plot": "A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.", "title": "The Benchwarmers"} {"plot": "A young boy is bequeathed the ownership of a professional baseball team.", "title": "Little Big League"} {"plot": "A trained chimpanzee plays third base for a minor-league baseball team.", "title": "Ed"}
검색 를 좁힙니다.
Atlas Search 복잡한 쿼리를 빌드 하고 사용 사례 에 맞는 보다 구체적인 결과를 조회 사용할 수 있는 여러 연산자 를 제공합니다. 복합 연산자 사용하여 여러 연산자를 단일 쿼리 로 결합하도록 $search
쿼리 업데이트합니다.
복합 쿼리 사용하도록
RunQuery.java
을(를) 수정합니다.이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
plot
필드baseball
라는 단어가 포함되어야 합니다.genres
필드에는Comedy
또는Romance
가 포함되어서는 안 됩니다.
1 import java.util.Arrays; 2 import java.util.List; 3 import static com.mongodb.client.model.Aggregates.limit; 4 import static com.mongodb.client.model.Aggregates.project; 5 import static com.mongodb.client.model.Projections.excludeId; 6 import static com.mongodb.client.model.Projections.fields; 7 import static com.mongodb.client.model.Projections.include; 8 import com.mongodb.client.MongoClient; 9 import com.mongodb.client.MongoClients; 10 import com.mongodb.client.MongoCollection; 11 import com.mongodb.client.MongoDatabase; 12 import org.bson.Document; 13 14 public class RunQuery { 15 public static void main( String[] args ) { 16 String uri = "<connection-string>"; 17 18 try (MongoClient mongoClient = MongoClients.create(uri)) { 19 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 20 MongoCollection<Document> collection = database.getCollection("movies"); 21 22 Document compound = new Document("must", Arrays.asList( 23 new Document("text", new Document("query", "baseball").append("path", "plot")))) 24 .append("mustNot", Arrays.asList( 25 new Document("text", new Document("query", Arrays.asList("Comedy", "Romance")).append("path", "genres")))); 26 27 Document searchStage = new Document("$search", 28 new Document("index", "default") 29 .append("compound", compound)); 30 31 collection.aggregate(Arrays.asList( 32 searchStage, 33 limit(3), 34 project(fields(excludeId(), include("title", "plot", "genres")))) 35 ).forEach(doc -> System.out.println(doc.toJson())); 36 } 37 } 38 } <connection-string>
을(를) 지정한 다음 쿼리 실행 .javac RunQuery.java java RunQuery {"plot": "The story of the life and career of the famed baseball player, Lou Gehrig.", "genres": ["Biography", "Drama", "Family"], "title": "The Pride of the Yankees"} {"plot": "Babe Ruth becomes a baseball legend but is unheroic to those who know him.", "genres": ["Biography", "Drama", "Sport"], "title": "The Babe"} {"plot": "Dominican baseball star Miguel \"Sugar\" Santos is recruited to play in the U.S. minor-leagues.", "genres": ["Drama", "Sport"], "title": "Sugar"}
결과를 처리합니다.
Atlas Search Atlas Search 쿼리 결과를 추가로 프로세스 데 사용할 수 있는 여러 검색 옵션을 제공합니다. 쿼리 에 정렬 옵션을 추가하여 결과를 특정 순서로 표시합니다.
RunQuery.java
를 수정하여 정렬 옵션을 추가합니다.이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
plot
필드baseball
라는 단어가 포함되어야 합니다.genres
필드에는Comedy
또는Romance
가 포함되어서는 안 됩니다.released
날짜 필드 기준으로 결과를 내림차순으로 정렬합니다. Atlas Search 가장 최근 영화를 먼저 반환합니다.$limit 및 $ 프로젝트 단계는 3 문서와
title
,plot
,genres
및released
필드만 반환합니다.
1 import java.util.Arrays; 2 import java.util.List; 3 import static com.mongodb.client.model.Aggregates.limit; 4 import static com.mongodb.client.model.Aggregates.project; 5 import static com.mongodb.client.model.Projections.excludeId; 6 import static com.mongodb.client.model.Projections.fields; 7 import static com.mongodb.client.model.Projections.include; 8 import com.mongodb.client.MongoClient; 9 import com.mongodb.client.MongoClients; 10 import com.mongodb.client.MongoCollection; 11 import com.mongodb.client.MongoDatabase; 12 import org.bson.Document; 13 14 public class RunQuery { 15 public static void main( String[] args ) { 16 String uri = "<connection-string>"; 17 18 try (MongoClient mongoClient = MongoClients.create(uri)) { 19 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 20 MongoCollection<Document> collection = database.getCollection("movies"); 21 22 Document compound = new Document("must", Arrays.asList( 23 new Document("text", new Document("query", "baseball").append("path", "plot")))) 24 .append("mustNot", Arrays.asList( 25 new Document("text", new Document("query", Arrays.asList("Comedy", "Romance")).append("path", "genres")))); 26 27 Document searchStage = new Document("$search", 28 new Document("index", "default") 29 .append("compound", compound) 30 .append("sort", new Document("released", -1))); 31 32 collection.aggregate(Arrays.asList( 33 searchStage, 34 limit(3), 35 project(fields(excludeId(), include("title", "plot", "genres", "released")))) 36 ).forEach(doc -> System.out.println(doc.toJson())); 37 } 38 } 39 } <connection-string>
을(를) 지정한 다음 쿼리 실행 .javac RunQuery.java java RunQuery {"plot": "A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.", "genres": ["Biography", "Drama", "Sport"], "title": "Million Dollar Arm", "released": {"$date": "2014-05-16T00:00:00Z"}} {"plot": "A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.", "genres": ["Biography", "Drama", "History"], "title": "Kano", "released": {"$date": "2014-02-27T00:00:00Z"}} {"plot": "12-year-old Josh is a mixed race boy and a promising baseball player. He is abused by his mother's boyfriend Byrd, and neglected by his mother Debbie. He forges his own path in life when ...", "genres": ["Drama"], "title": "Calloused Hands", "released": {"$date": "2013-03-03T00:00:00Z"}}
기본 쿼리 실행합니다.
텍스트 연산자 사용하여 기본 $search
쿼리 실행합니다.
RunQuery.kt
(이)라는 새 파일 만들고 다음 코드를 붙여넣습니다.이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Filters.eq 4 import com.mongodb.client.model.Projections.* 5 import com.mongodb.kotlin.client.coroutine.MongoClient 6 import kotlinx.coroutines.runBlocking 7 import org.bson.Document 8 9 fun main() { 10 // establish connection and set namespace 11 val uri = "<connection-string>" 12 val mongoClient = MongoClient.create(uri) 13 val database = mongoClient.getDatabase("sample_mflix") 14 val collection = database.getCollection<Document>("movies") 15 16 runBlocking { 17 // define query 18 val agg = Document("query", "baseball").append("path","plot") 19 20 // run query and print results 21 val resultsFlow = collection.aggregate<Document>( 22 listOf( 23 eq("\$search", eq("text", agg)), 24 limit(3), 25 project(fields(excludeId(), include("title", "plot"))) 26 ) 27 ) 28 resultsFlow.collect { println(it) } 29 } 30 mongoClient.close() 31 } <connection-string>
을(를) 지정한 다음 쿼리 실행 .IDE에서
RunQuery.kt
프로그램을 실행하면 다음 문서가 인쇄됩니다.Document{{plot=The story of the life and career of the famed baseball player, Lou Gehrig., genres=[Biography, Drama, Family], title=The Pride of the Yankees}} Document{{plot=Babe Ruth becomes a baseball legend but is unheroic to those who know him., genres=[Biography, Drama, Sport], title=The Babe}} Document{{plot=Dominican baseball star Miguel "Sugar" Santos is recruited to play in the U.S. minor-leagues., genres=[Drama, Sport], title=Sugar}}
검색 를 좁힙니다.
Atlas Search 복잡한 쿼리를 빌드 하고 사용 사례 에 맞는 보다 구체적인 결과를 조회 사용할 수 있는 여러 연산자 를 제공합니다. 복합 연산자 사용하여 여러 연산자를 단일 쿼리 로 결합하도록 $search
쿼리 업데이트합니다.
복합 쿼리 사용하도록
RunQuery.kt
을(를) 수정합니다.이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
plot
필드baseball
라는 단어가 포함되어야 합니다.genres
필드에는Comedy
또는Romance
가 포함되어서는 안 됩니다.
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Filters.eq 4 import com.mongodb.client.model.Projections.* 5 import com.mongodb.kotlin.client.coroutine.MongoClient 6 import kotlinx.coroutines.runBlocking 7 import org.bson.Document 8 9 fun main() { 10 // establish connection and set namespace 11 val uri = "<connection-string>" 12 val mongoClient = MongoClient.create(uri) 13 val database = mongoClient.getDatabase("sample_mflix") 14 val collection = database.getCollection<Document>("movies") 15 16 runBlocking { 17 // define query 18 val compoundQuery = Document( 19 "must", listOf( 20 Document("text", Document("query", "baseball") 21 .append("path", "plot")) 22 ) 23 ) 24 .append( 25 "mustNot", listOf( 26 Document("text", Document("query", listOf("Comedy", "Romance")) 27 .append("path", "genres")) 28 ) 29 ) 30 31 // run query and print results 32 val resultsFlow = collection.aggregate<Document>( 33 listOf( 34 eq("\$search", eq("compound", compoundQuery)), 35 limit(3), 36 project(fields( 37 excludeId(), 38 include("title", "plot", "genres") 39 )) 40 ) 41 ) 42 resultsFlow.collect { println(it) } 43 } 44 mongoClient.close() 45 } <connection-string>
을(를) 지정한 다음 쿼리 실행 .IDE에서
RunQuery.kt
프로그램을 실행하면 다음 문서가 인쇄됩니다.Document{{plot=The story of the life and career of the famed baseball player, Lou Gehrig., genres=[Biography, Drama, Family], title=The Pride of the Yankees}} Document{{plot=Babe Ruth becomes a baseball legend but is unheroic to those who know him., genres=[Biography, Drama, Sport], title=The Babe}} Document{{plot=Dominican baseball star Miguel "Sugar" Santos is recruited to play in the U.S. minor-leagues., genres=[Drama, Sport], title=Sugar}}
결과를 처리합니다.
Atlas Search Atlas Search 쿼리 결과를 추가로 프로세스 데 사용할 수 있는 여러 검색 옵션을 제공합니다. 쿼리 에 정렬 옵션을 추가하여 결과를 특정 순서로 표시합니다.
RunQuery.kt
를 수정하여 정렬 옵션을 추가합니다.이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
plot
필드baseball
라는 단어가 포함되어야 합니다.genres
필드에는Comedy
또는Romance
가 포함되어서는 안 됩니다.released
날짜 필드 기준으로 결과를 내림차순으로 정렬합니다. Atlas Search 가장 최근 영화를 먼저 반환합니다.$limit 및 $ 프로젝트 단계는 3 문서와
title
,plot
,genres
및released
필드만 반환합니다.
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Filters.eq 4 import com.mongodb.client.model.Projections.* 5 import com.mongodb.kotlin.client.coroutine.MongoClient 6 import kotlinx.coroutines.runBlocking 7 import org.bson.Document 8 9 fun main() { 10 // establish connection and set namespace 11 val uri = "<connection-string>" 12 val mongoClient = MongoClient.create(uri) 13 val database = mongoClient.getDatabase("sample_mflix") 14 val collection = database.getCollection<Document>("movies") 15 16 runBlocking { 17 // define query 18 val compoundQuery = Document( 19 "must", listOf( 20 Document("text", Document("query", "baseball") 21 .append("path", "plot")) 22 ) 23 ) 24 .append( 25 "mustNot", listOf( 26 Document("text", Document("query", listOf("Comedy", "Romance")) 27 .append("path", "genres")) 28 ) 29 ) 30 31 // sort configuration 32 val sortConfig = Document("released", -1) 33 34 // run query and print results 35 val resultsFlow = collection.aggregate<Document>( 36 listOf( 37 Document("\$search", Document("compound", compoundQuery).append("sort", sortConfig)), 38 limit(3), 39 project(fields( 40 excludeId(), 41 include("title", "plot", "genres", "released") 42 )) 43 ) 44 ) 45 resultsFlow.collect { println(it) } 46 } 47 mongoClient.close() 48 } <connection-string>
을(를) 지정한 다음 쿼리 실행 .IDE에서
RunQuery.kt
프로그램을 실행하면 다음 문서가 인쇄됩니다.Document{{plot=A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball., genres=[Biography, Drama, Sport], title=Million Dollar Arm, released=Thu May 15 19:00:00 CDT 2014}} Document{{plot=A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament., genres=[Biography, Drama, History], title=Kano, released=Wed Feb 26 18:00:00 CST 2014}} Document{{plot=12-year-old Josh is a mixed race boy and a promising baseball player. He is abused by his mother's boyfriend Byrd, and neglected by his mother Debbie. He forges his own path in life when ..., genres=[Drama], title=Calloused Hands, released=Sat Mar 02 18:00:00 CST 2013}}
기본 쿼리 실행합니다.
텍스트 연산자 사용하여 기본 $search
쿼리 실행합니다.
run-query.js
(이)라는 새 파일 만들고 다음 코드를 붙여넣습니다.이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
1 const { MongoClient } = require("mongodb"); 2 3 async function main() { 4 // Replace the placeholder with your connection string 5 const uri = "<connection-string>"; 6 const client = new MongoClient(uri); 7 8 try { 9 await client.connect(); 10 const database = client.db("sample_mflix"); 11 const movies = database.collection("movies"); 12 13 const query = [ 14 { 15 $search: 16 { 17 text: { 18 query: "baseball", 19 path: "plot", 20 }, 21 } 22 }, 23 { 24 $limit: 3, 25 }, 26 { 27 $project: { 28 _id: 0, 29 title: 1, 30 plot: 1, 31 }, 32 }, 33 ]; 34 35 const cursor = movies.aggregate(query); 36 await cursor.forEach(doc => console.log(doc)); 37 } finally { 38 await client.close(); 39 } 40 } 41 42 main().catch(console.error); <connection-string>
을(를) 지정한 다음 쿼리 실행 .node run-query.js { plot: 'A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.', title: 'The Benchwarmers' } { plot: 'A young boy is bequeathed the ownership of a professional baseball team.', title: 'Little Big League' } { plot: 'A trained chimpanzee plays third base for a minor-league baseball team.', title: 'Ed' }
검색 를 좁힙니다.
Atlas Search 복잡한 쿼리를 빌드 하고 사용 사례 에 맞는 보다 구체적인 결과를 조회 사용할 수 있는 여러 연산자 를 제공합니다. 복합 연산자 사용하여 여러 연산자를 단일 쿼리 로 결합하도록 $search
쿼리 업데이트합니다.
복합 쿼리 사용하도록
run-query.js
을(를) 수정합니다.이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
plot
필드baseball
라는 단어가 포함되어야 합니다.genres
필드에는Comedy
또는Romance
가 포함되어서는 안 됩니다.
1 const { MongoClient } = require("mongodb"); 2 3 async function main() { 4 // Replace the placeholder with your connection string 5 const uri = "<connection-string>"; 6 const client = new MongoClient(uri); 7 8 try { 9 await client.connect(); 10 const database = client.db("sample_mflix"); 11 const movies = database.collection("movies"); 12 13 const query = [ 14 { 15 $search: { 16 compound: { 17 must: [ 18 { 19 text: { 20 query: "baseball", 21 path: "plot", 22 } 23 } 24 ], 25 mustNot: [ 26 { 27 text: { 28 query: ["Comedy", "Romance"], 29 path: "genres", 30 }, 31 } 32 ] 33 } 34 } 35 }, 36 { 37 $limit: 3 38 }, 39 { 40 $project: { 41 _id: 0, 42 title: 1, 43 plot: 1, 44 genres: 1 45 } 46 } 47 ]; 48 49 const cursor = movies.aggregate(query); 50 await cursor.forEach(doc => console.log(doc)); 51 } finally { 52 await client.close(); 53 } 54 } 55 56 main().catch(console.error); <connection-string>
을(를) 지정한 다음 쿼리 실행 .node run-query.js { plot: 'The story of the life and career of the famed baseball player, Lou Gehrig.', genres: [ 'Biography', 'Drama', 'Family' ], title: 'The Pride of the Yankees' } { plot: 'Babe Ruth becomes a baseball legend but is unheroic to those who know him.', genres: [ 'Biography', 'Drama', 'Sport' ], title: 'The Babe' } { plot: 'Dominican baseball star Miguel "Sugar" Santos is recruited to play in the U.S. minor-leagues.', genres: [ 'Drama', 'Sport' ], title: 'Sugar' }
결과를 처리합니다.
Atlas Search Atlas Search 쿼리 결과를 추가로 프로세스 데 사용할 수 있는 여러 검색 옵션을 제공합니다. 쿼리 에 정렬 옵션을 추가하여 결과를 특정 순서로 표시합니다.
run-query.js
를 수정하여 정렬 옵션을 추가합니다.이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
plot
필드baseball
라는 단어가 포함되어야 합니다.genres
필드에는Comedy
또는Romance
가 포함되어서는 안 됩니다.released
날짜 필드 기준으로 결과를 내림차순으로 정렬합니다. Atlas Search 가장 최근 영화를 먼저 반환합니다.$limit 및 $ 프로젝트 단계는 3 문서와
title
,plot
,genres
및released
필드만 반환합니다.
1 const { MongoClient } = require("mongodb"); 2 3 async function main() { 4 // Replace the placeholder with your connection string 5 const uri = "<connection-string>"; 6 const client = new MongoClient(uri); 7 8 try { 9 await client.connect(); 10 const database = client.db("sample_mflix"); 11 const movies = database.collection("movies"); 12 13 const query = [ 14 { 15 $search: { 16 compound: { 17 must: [ 18 { 19 text: { 20 query: "baseball", 21 path: "plot", 22 } 23 } 24 ], 25 mustNot: [ 26 { 27 text: { 28 query: ["Comedy", "Romance"], 29 path: "genres", 30 } 31 } 32 ] 33 }, 34 sort: { 35 released: -1 36 } 37 } 38 }, 39 { 40 $limit: 3 41 }, 42 { 43 $project: { 44 _id: 0, 45 title: 1, 46 plot: 1, 47 genres: 1, 48 released: 1 49 } 50 } 51 ]; 52 53 const cursor = movies.aggregate(query); 54 await cursor.forEach(doc => console.log(doc)); 55 } finally { 56 await client.close(); 57 } 58 } 59 60 main().catch(console.error); <connection-string>
을(를) 지정한 다음 쿼리 실행 .node run-query.js { plot: 'A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.', genres: [ 'Biography', 'Drama', 'Sport' ], title: 'Million Dollar Arm', released: 2014-05-16T00:00:00.000Z } { plot: 'A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.', genres: [ 'Biography', 'Drama', 'History' ], title: 'Kano', released: 2014-02-27T00:00:00.000Z } { plot: "12-year-old Josh is a mixed race boy and a promising baseball player...", genres: [ 'Drama' ], title: 'Calloused Hands', released: 2013-03-03T00:00:00.000Z }
기본 쿼리 실행합니다.
텍스트 연산자 사용하여 기본 $search
쿼리 실행합니다.
run_query.py
(이)라는 새 파일 만들고 다음 코드를 붙여넣습니다.이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
1 import pymongo 2 3 client = pymongo.MongoClient('<connection-string>') 4 result = client['sample_mflix']['movies'].aggregate([ 5 { 6 '$search': 7 { 8 'text': { 9 'query': 'baseball', 10 'path': 'plot' 11 } 12 } 13 }, 14 { 15 '$limit': 3 16 }, 17 { 18 '$project': { 19 '_id': 0, 20 'title': 1, 21 'plot': 1 22 } 23 } 24 ]) 25 26 for i in result: 27 print(i) <connection-string>
을(를) 지정한 다음 쿼리 실행 .python run_query.py {'plot': 'A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.', 'title': 'The Benchwarmers'} {'plot': 'A young boy is bequeathed the ownership of a professional baseball team.', 'title': 'Little Big League'} {'plot': 'A trained chimpanzee plays third base for a minor-league baseball team.', 'title': 'Ed'}
검색 를 좁힙니다.
Atlas Search 복잡한 쿼리를 빌드 하고 사용 사례 에 맞는 보다 구체적인 결과를 조회 사용할 수 있는 여러 연산자 를 제공합니다. 복합 연산자 사용하여 여러 연산자를 단일 쿼리 로 결합하도록 $search
쿼리 업데이트합니다.
복합 쿼리 사용하도록
run_query.py
을(를) 수정합니다.이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
plot
필드baseball
라는 단어가 포함되어야 합니다.genres
필드에는Comedy
또는Romance
가 포함되어서는 안 됩니다.
1 import pymongo 2 3 client = pymongo.MongoClient('<connection-string>') 4 result = client['sample_mflix']['movies'].aggregate([ 5 { 6 '$search': { 7 'compound': { 8 'must': [ 9 { 10 'text': { 11 'query': 'baseball', 12 'path': 'plot' 13 } 14 } 15 ], 16 'mustNot': [ 17 { 18 'text': { 19 'query': ['Comedy', 'Romance'], 20 'path': 'genres' 21 } 22 } 23 ] 24 } 25 } 26 }, 27 { 28 '$limit': 3 29 }, 30 { 31 '$project': { 32 '_id': 0, 33 'title': 1, 34 'plot': 1, 35 'genres': 1 36 } 37 } 38 ]) 39 40 for i in result: 41 print(i) <connection-string>
을(를) 지정한 다음 쿼리 실행 .python run_query.py {'plot': 'The story of the life and career of the famed baseball player, Lou Gehrig.', 'genres': ['Biography', 'Drama', 'Family'], 'title': 'The Pride of the Yankees'} {'plot': 'Babe Ruth becomes a baseball legend but is unheroic to those who know him.', 'genres': ['Biography', 'Drama', 'Sport'], 'title': 'The Babe'} {'plot': 'Dominican baseball star Miguel "Sugar" Santos is recruited to play in the U.S. minor-leagues.', 'genres': ['Drama', 'Sport'], 'title': 'Sugar'}
결과를 처리합니다.
Atlas Search Atlas Search 쿼리 결과를 추가로 프로세스 데 사용할 수 있는 여러 검색 옵션을 제공합니다. 쿼리 에 정렬 옵션을 추가하여 결과를 특정 순서로 표시합니다.
run_query.py
를 수정하여 정렬 옵션을 추가합니다.이 쿼리 에는 다음과 같은 검색 기준이 있습니다.
plot
필드baseball
라는 단어가 포함되어야 합니다.genres
필드에는Comedy
또는Romance
가 포함되어서는 안 됩니다.released
날짜 필드 기준으로 결과를 내림차순으로 정렬합니다. Atlas Search 가장 최근 영화를 먼저 반환합니다.$limit 및 $ 프로젝트 단계는 3 문서와
title
,plot
,genres
및released
필드만 반환합니다.
1 import pymongo 2 3 client = pymongo.MongoClient('<connection-string>') 4 result = client['sample_mflix']['movies'].aggregate([ 5 { 6 '$search': { 7 'compound': { 8 'must': [ 9 { 10 'text': { 11 'query': 'baseball', 12 'path': 'plot' 13 } 14 } 15 ], 16 'mustNot': [ 17 { 18 'text': { 19 'query': ['Comedy', 'Romance'], 20 'path': 'genres' 21 } 22 } 23 ] 24 }, 25 'sort': { 26 'released': -1 27 } 28 } 29 }, 30 { 31 '$limit': 3 32 }, 33 { 34 '$project': { 35 '_id': 0, 36 'title': 1, 37 'plot': 1, 38 'genres': 1, 39 'released': 1 40 } 41 } 42 ]) 43 44 for i in result: 45 print(i) <connection-string>
을(를) 지정한 다음 쿼리 실행 .python run_query.py {'plot': 'A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.', 'genres': ['Biography', 'Drama', 'Sport'], 'title': 'Million Dollar Arm', 'released': datetime.datetime(2014, 5, 16, 0, 0)} {'plot': 'A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.', 'genres': ['Biography', 'Drama', 'History'], 'title': 'Kano', 'released': datetime.datetime(2014, 2, 27, 0, 0)} {'plot': "12-year-old Josh is a mixed race boy and a promising baseball player...", 'genres': ['Drama'], 'title': 'Calloused Hands', 'released': datetime.datetime(2013, 3, 3, 0, 0)}
학습 계속하기
자동 완성 및 부분 일치 쿼리 실행
Atlas Search 사용하여 부분 단어에 대한 결과를 반환하는 자동 완성 및 부분 쿼리를 실행 수 있습니다. 이는 애플리케이션의 검색 필드 에 더 많은 문자를 입력할수록 결과를 더 정확하게 조회 데 유용합니다.자동 완성 연산자 사용하려면 필드를 Atlas Search 자동 완성 유형으로 인덱스 해야 합니다.
시작하려면 자동 완성 및 부분 일치 Atlas Search 쿼리를 실행하는 방법을 참조하세요.
패싯을 사용하여 검색 결과 그룹화
Atlas Search 사용하여 문자열, 날짜 또는 숫자 값을 기준으로 검색 결과를 그룹 패싯 쿼리를 실행 수 있습니다. 패싯 수집기를 사용하려면 패싯 정의가 포함된 인덱스 생성해야 합니다.
시작하려면 Atlas Search 에서 패싯을 사용하는 방법을 참조하세요.
Atlas Search 플레이그라운드 사용
Atlas Search 사용하면 boolean
date
number
인덱싱된,,, objectId
및 필드 값에서 오름차순 또는 내림차순으로 결과를 정렬할 수 string
있습니다. 자세히 학습 Atlas Search 결과 정렬을 참조하세요.
코스로 배우기
Atlas Search에 대해 자세히 알아보려면 MongoDB University의 Atlas Search 과정 1단원을 수강할 수 있습니다. 2.25시간 분량으로, Atlas Search에 대한 개요와 Atlas Search 인덱스를 만드는 방법, 다양한 연산자와 함께 $search
를 사용하는 방법, 검색 패싯을 생성하는 방법에 대한 강의가 포함되어 있습니다.
보면서 배우기
다음 동영상을 시청하여 Atlas Search 에 대해 자세히 학습 수도 있습니다.
Atlas 및 Atlas Search의 개요를 시청하고 데이터에 대한 Atlas Search 설정을 시작하십시오. 이 동영상에서는 클러스터에 샘플 데이터를 로드하고, Atlas Search 인덱스를 만들고 Search Tester, Data Explorer을 사용하여 샘플 쿼리를 실행하는 방법을 보여 줍니다.
지속 시간 소요 시간: 10분
다음 동영상을 따라 보면서 Atlas Search 인덱스 구성하고 애플리케이션 에서 쿼리를 실행 방법을 학습 .
동영상 길이: 7분
레스토랑 찾기 데모 애플리케이션 에 대한 Atlas Search 쿼리를 빌드 방법을 보여주는 다음 동영상 튜토리얼 안내를 따르세요.
소요 시간: 20분