Docs Menu
Docs Home
/ /

MongoDB Search Community에 연결

예상 완료 시간: 5분

MongoDB Search Community Edition을 사용하려면 MongoDB Community 배포서버 에 연결해야 합니다. 다음 방법을 사용하여 MongoDB Community 배포서버 에 연결합니다.

  • MongoDB Shell은 MongoDB에 대한 대화형 명령줄 인터페이스입니다.

  • MongoDB Compass, MongoDB 데이터를 위한 GUI입니다.

  • MongoDB 운전자. 사용 가능한 모든 언어를 보려면 MongoDB 드라이버 설명서를 참조하세요.

언어 선택 드롭다운 메뉴를 사용하여 이 페이지의 절차에 대한 클라이언트를 설정하다.

시작하기 전에 다음 전제 조건이 있어야 합니다.

  • MongoDB CommunityMongoDB Search Community

    참고

    mongodmongot 프로세스가 모두 실행 중인지 확인합니다.

  • 연결할 유효한 사용자 이름 과 비밀번호

    복제본 세트 에서 사용자를 아직 생성하지 않은 경우 터미널에서 다음 명령을 실행 사용자를 생성합니다.

    1. mongosh를 사용하여 복제본 세트 에 연결합니다.

      mongosh
    2. 다음 명령을 실행하여 admin 데이터베이스에 searchCoordinator 역할을 가진 mongotUser 사용자를 생성합니다. MongoDB mongotUser 사용자를 사용하여 mongodmongot 를 인증합니다.

      use admin
      db.createUser( {
      user: "mongotUser",
      pwd: passwordPrompt(),
      roles: [ { role: "searchCoordinator", db: "admin" } ]
      } )

      역할 readAnyDatabase 가진 사용자에게는 searchCoordinator __mdb_internal_search 데이터베이스 에 대한 권한 및 쓰기 (write) 권한이 있습니다.

      중요

      __mdb_internal_search 데이터베이스 의 내용을 수정하지 마세요.

  • 복제본 세트 에 대한 연결 문자열

    복제본 세트 의 연결 문자열 에는 모든 멤버 노드가 포함됩니다. 따라서 연결하려면 복제본 세트 이름과 모든 복제본 세트 멤버의 호스트 이름 또는 IP 주소 및 포트가 필요합니다.

  • MongoDB Compass

  • 터미널

  • 텍스트 편집기

  • dotnet

  • AC# 프로젝트

    프로젝트를 초기화하려면 프로젝트 디렉토리에서 dotnet new console 명령을 실행합니다. 자세한 내용은 C# 빠른 시작을 참조하세요.

  • 터미널

  • 텍스트 편집기

  • Go

  • 고 (Go) 프로젝트

    프로젝트를 초기화하려면 go mod 명령을 사용합니다. 자세한 내용은 Go 빠른 시작을 참조하세요.

  • MongoDB Go 드라이버

    고 (Go) 운전자 및 운전자 종속성을 다운로드 하여 설치하려면 다음 명령을 실행 .

    go get go.mongodb.org/mongo-driver/v2/mongo
    go get github.com/joho/godotenv

Node.js 드라이버를 설치하려면 터미널 프롬프트에서 다음 명령을 실행합니다.

npm install mongodb --save
  • 터미널

  • 텍스트 편집기

  • Python

    사용 중인 운영 체제에 맞는 Python의 최신 버전을 다운로드하려면 Python 다운로드 페이지를 참조하세요.

  • pip 패키지 설치 프로그램

    Python 2.7.9 및 Python 3.4부터 https://python.org 에서 다운로드한 패키지에는 pip가 포함됩니다.

    pip 를 수동으로 설치하려면 pip 설치 페이지를 참조하세요. 이 패키지 에는 Python 포함되어 있습니다.

복제본 세트의 연결 문자열 을 사용하여 원하는 클라이언트로 복제본 세트에 연결합니다. mongotmongod 를 올바르게 구성했는지 확인하려면 검색 인덱스를 검색하는 명령을 실행 하면 됩니다.

1
2

예시 를 들어, 명령의 자리 표시자 값을 바꾼 후 다음과 유사한 명령을 실행 연결합니다.

mongosh -u <USER-NAME> -p <USER-PASSWORD> --authenticationDatabase "<AUTHENTICATION-DB>" --host <HOST-NAME> --port <PORT-NUMBER>

이제 복제본 세트 에 연결되고 터미널에 다음과 유사한 내용이 표시되어야 합니다.

rs0 [direct: primary] test>
3

확인하려면 다음 단계를 수행하세요.

  1. 이름이 movies인 컬렉션 에 문서 추가합니다.

    db.movies.insertOne({"title": "Back to the Future"})
    {
    acknowledged: true,
    insertedId: ObjectId('67e42132a1cd6f443d5337b1')
    }
  2. movies 컬렉션 에 대한 모든 검색 인덱스를 조회합니다.

    db.runCommand({"listSearchIndexes": "movies"});
    {
    cursor: { id: 0, ns: 'test.movies', firstBatch: [] },
    ok: 1,
    '$clusterTime': {
    clusterTime: Timestamp({ t: 1743003975, i: 1 }),
    signature: {
    hash: Binary.createFromBase64('H1nlTKJBRCfZXrWul9AhGRVpIQ0=', 0),
    keyId: Long('7484323578087735302')
    }
    },
    operationTime: Timestamp({ t: 1743003975, i: 1 })
    }

    참고

    샘플 코드가 movies 컬렉션 에 대한 인덱스 생성하지 않았으므로 결과에는 인덱스가 포함되지 않습니다.

자세히 학습 배포서버에 연결을 참조하세요.

1
2

자세한 내용은 MongoDB에 연결을 참조하세요.

다음 샘플 애플리케이션 연결 문자열 사용하여 복제본 세트 에 연결하고 성공적인 연결을 확인하기 위해 핑 보냅니다. 샘플 애플리케이션 테스트하려면 다음 단계를 수행하세요.

  1. 이름이 connect인 새 디렉토리를 만들고 dotnet new 명령을 사용하여 프로젝트를 초기화합니다.

    mkdir connect
    cd connect
    dotnet new console
  2. 다음 명령을 실행하여 .NET/C# 드라이버를 프로젝트에 종속성으로 추가합니다.

    dotnet add package MongoDB.Driver
  3. Program.cs 파일 에서 연결 설정을 정의합니다.

    Program.cs 파일의 내용을 다음 코드로 바꿉니다. 샘플 코드는 다음을 수행합니다.

    • 로컬 배포서버 서버에 연결합니다.

    • test 데이터베이스 에 하나 문서 포함된 movies 컬렉션 삽입합니다.

    • 컬렉션 에 대한 모든 검색 인덱스를 조회합니다.

    1using MongoDB.Bson;
    2using MongoDB.Driver;
    3
    4public class Connect
    5{
    6 // Replace the following with your connection string
    7 private const string MongoConnectionString = "<CONNECTION-STRING>";
    8
    9 public static void Main(string[] args)
    10 {
    11 // Connect to your replica set
    12 var client = new MongoClient(MongoConnectionString);
    13
    14 // Send a ping to confirm a successful connection
    15 try {
    16 var result = client.GetDatabase("admin").RunCommand<BsonDocument>(new BsonDocument("ping", 1));
    17 Console.WriteLine("Successfully connected to Replica Set");
    18 }
    19 catch (Exception e) { Console.WriteLine(e);}
    20
    21 // Insert a document to a collection
    22 var database = client.GetDatabase("test");
    23 var collection = database.GetCollection<BsonDocument>("movies");
    24 var movieDocument = new BsonDocument{{"title", "Back to the Future"}};
    25 try {
    26 collection.InsertOne(movieDocument);
    27 Console.WriteLine("Document inserted successfully.");
    28 }
    29 catch (Exception e) {
    30 Console.WriteLine($"Insertion error: {e.Message}");
    31 }
    32
    33 // List search indexes
    34 try {
    35 var result = collection.SearchIndexes.List().ToList();
    36 if (indexes.Count == 0) {
    37 Console.WriteLine("No indexes found on the collection.");
    38 }
    39 else {
    40 Console.WriteLine("Indexes on the collection:");
    41 foreach (var index in indexes)
    42 {
    43 Console.WriteLine(index.ToJson());
    44 }
    45 }
    46 }
    47 catch (Exception e) {
    48 Console.WriteLine($"Error listing indexes: {e.Message}");
    49 }
    50 }
    51}
  4. 자리 표시자(7줄)를 연결 문자열 로 바꾸고 파일 을 저장합니다.

  5. 애플리케이션 실행합니다.

    dotnet run Program.cs
    Successfully connected to MongoDB.
    Document inserted successfully.
    No indexes found on the collection.

    참고

    샘플 코드가 movies 컬렉션 에 대한 인덱스 생성하지 않았으므로 결과에는 인덱스가 포함되지 않습니다.

자세한 사항은 연결 옵션을 참조하세요.

다음 샘플 애플리케이션 연결 문자열 사용하여 복제본 세트 에 연결하고 성공적인 연결을 확인하기 위해 핑 보냅니다. 다음 단계에 따라 샘플 애플리케이션 테스트합니다.

  1. 이름이 connect인 새 디렉토리를 만들고 go mod 명령을 사용하여 프로젝트를 초기화합니다.

    mkdir connect
    cd connect
    go mod init connect
  2. .go 파일 에서 연결 설정을 정의합니다.

    프로젝트에 connect.go라는 새 파일을 만들고 다음 코드를 붙여넣습니다.

    1package main
    2
    3import (
    4 "context"
    5 "encoding/json"
    6 "fmt"
    7 "log"
    8
    9 "go.mongodb.org/mongo-driver/bson"
    10 "go.mongodb.org/mongo-driver/mongo"
    11 "go.mongodb.org/mongo-driver/mongo/options"
    12 "go.mongodb.org/mongo-driver/mongo/readpref"
    13)
    14
    15type Movie struct {
    16 Title string `bson:"title"`
    17}
    18
    19func main() {
    20 // Replace with your connection string
    21 uri := "<CONNECTION-STRING>"
    22
    23 // Connect to MongoDB
    24 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
    25 if err != nil {
    26 log.Fatalf("Failed to connect to MongoDB: %v", err)
    27 }
    28 defer func() {
    29 if err = client.Disconnect(context.TODO()); err != nil {
    30 log.Fatalf("Failed to disconnect MongoDB client: %v", err)
    31 }
    32 }()
    33
    34 // Ping to confirm connection
    35 if err := client.Ping(context.TODO(), readpref.Primary()); err != nil {
    36 log.Fatalf("Failed to ping MongoDB: %v", err)
    37 }
    38 fmt.Println("Successfully connected to MongoDB")
    39
    40 // Insert a document to a collection
    41 coll := client.Database("test").Collection("movies")
    42 newMovie := Movie{Title: "Back to the Future"}
    43 result, err := coll.InsertOne(context.TODO(), newMovie)
    44 if err != nil {
    45 log.Fatalf("Failed to insert document: %v", err)
    46 }
    47 fmt.Printf("Inserted document ID: %v\n", result.InsertedID)
    48
    49 // List search indexes
    50 listOpts := options.ListSearchIndexesOptions{}
    51 ctx := context.TODO()
    52 cursor, err := coll.SearchIndexes().List(ctx, nil, &listOpts)
    53 if err != nil {
    54 log.Fatalf("Failed to list search indexes: %v", err)
    55 }
    56
    57 var results []bson.D
    58 if err = cursor.All(ctx, &results); err != nil {
    59 log.Fatalf("Failed to iterate over cursor: %v", err)
    60 }
    61
    62 res, err := json.Marshal(results)
    63 if err != nil {
    64 log.Fatalf("Failed to marshal results to JSON: %v", err)
    65 }
    66 fmt.Println("Search indexes found:", string(res))
    67}
  3. 자리 표시자(15줄)를 연결 문자열 로 바꾸고 파일 을 저장합니다.

  4. 애플리케이션 실행합니다.

    go run connect.go
    Successfully connected to MongoDB
    Inserted document ID: ObjectID("67e42df345bc0b636fe340f0")
    Search indexes found: null

    참고

    샘플 코드가 movies 컬렉션 에 대한 인덱스 생성하지 않았으므로 결과에는 인덱스가 포함되지 않습니다.

자세히 학습 연결을 참조하세요.

다음 샘플 애플리케이션 연결 문자열 사용하여 복제본 세트 에 연결합니다. 샘플 애플리케이션 테스트하려면 다음 단계를 수행하세요.

  1. Java 클래스 파일 에서 연결 설정을 정의합니다.

    다음 코드를 Connect.java 파일 에 복사합니다.

    1import com.mongodb.ConnectionString;
    2import com.mongodb.MongoClientSettings;
    3import com.mongodb.MongoException;
    4import com.mongodb.ServerApi;
    5import com.mongodb.ServerApiVersion;
    6import com.mongodb.client.MongoClient;
    7import com.mongodb.client.MongoClients;
    8import com.mongodb.client.MongoCollection;
    9import com.mongodb.client.MongoCursor;
    10import com.mongodb.client.MongoDatabase;
    11import org.bson.BsonDocument;
    12import org.bson.BsonInt64;
    13import org.bson.Document;
    14import org.bson.conversions.Bson;
    15
    16public class Connect {
    17 public static void main(String[] args) {
    18 // Replace the placeholder with your Replica Set connection string
    19 String uri = "<CONNECTION-STRING>";
    20
    21 // Construct a ServerApi instance using the ServerApi.builder() method
    22 ServerApi serverApi = ServerApi.builder()
    23 .version(ServerApiVersion.V1)
    24 .build();
    25
    26 MongoClientSettings settings = MongoClientSettings.builder()
    27 .applyConnectionString(new ConnectionString(uri))
    28 .serverApi(serverApi)
    29 .build();
    30
    31 // Create a new client and connect to the server
    32 try (MongoClient mongoClient = MongoClients.create(settings)) {
    33 MongoDatabase adminDatabase = mongoClient.getDatabase("admin");
    34 try {
    35 // Send a ping to confirm a successful connection
    36 Bson command = new BsonDocument("ping", new BsonInt64(1));
    37 adminDatabase.runCommand(command);
    38 System.out.println("Successfully connected to Replica Set");
    39 } catch (MongoException e) {
    40 System.err.println("Ping failed: " + e);
    41 }
    42
    43 // Insert a document into a collection
    44 MongoDatabase database = mongoClient.getDatabase("test");
    45 MongoCollection<Document> collection = database.getCollection("movies");
    46 Document movieDocument = new Document("title", "Back to the Future");
    47 try {
    48 collection.insertOne(movieDocument);
    49 System.out.println("Document inserted successfully.");
    50 } catch (MongoException e) {
    51 System.err.println("Insertion failed: " + e);
    52 }
    53
    54 // List search indexes
    55 try (MongoCursor<Document> resultsCursor = collection.listSearchIndexes().iterator()) {
    56 System.out.println("Search indexes found:");
    57 while (resultsCursor.hasNext()) {
    58 System.out.println(resultsCursor.next().toJson());
    59 }
    60 } catch (MongoException e) {
    61 System.err.println("Error listing indexes: " + e);
    62 }
    63 } catch (MongoException e) {
    64 System.err.println("Failed to create MongoClient: " + e);
    65 }
    66 }
    67}
  2. 자리 표시자(14줄)를 연결 문자열 로 바꾸고 파일 을 저장합니다.

  3. IDE 또는 다음 명령을 사용하여 Connect.java 파일을 컴파일하고 실행합니다.

    javac Connect.java
    java Connect
    Successfully connected to Replica Set
    Document inserted successfully.
    Search indexes found:

    참고

    샘플 코드가 movies 컬렉션 에 대한 인덱스 생성하지 않았으므로 결과에는 인덱스가 포함되지 않습니다.

자세한 내용은 MongoDB에 연결을 참조하세요.

다음 샘플 애플리케이션 연결 문자열 사용하여 복제본 세트 에 연결하고 확인 메시지를 반환합니다. 샘플 애플리케이션 테스트하려면 다음 단계를 수행하세요.

  1. .js 파일 에서 연결 설정을 정의합니다.

    다음 코드를 connect.js 파일 에 복사합니다.

    1const { MongoClient } = require("mongodb");
    2
    3const url = "<CONNECTION-STRING>";
    4
    5// Connect to your Replica Set
    6const client = new MongoClient(url);
    7
    8async function run() {
    9 try {
    10 await client.connect();
    11 console.log("Successfully connected to Replica Set");
    12
    13 // Insert a document in a collection
    14 const database = client.db("test");
    15 const coll = database.collection("movies");
    16 const doc = { title: "Back to the Future" };
    17 const insertResult = await coll.insertOne(doc);
    18 console.log(`Document inserted with _id: ${insertResult.insertedId}`);
    19
    20 // List search indexes for the collection
    21 const searchIndexesResult = await coll.listSearchIndexes().toArray();
    22 console.log("Search indexes:", searchIndexesResult);
    23 } catch (err) {
    24 console.log("Error occurred:", err.stack);
    25 } finally {
    26 await client.close();
    27 }
    28}
    29
    30run().catch(console.dir);
  2. 자리 표시자(4줄)를 연결 문자열 로 바꾸고 파일 을 저장합니다.

  3. 다음 명령을 사용하여 샘플 애플리케이션 실행합니다.

    node connect.js
    Successfully connected to Replica Set
    Document inserted with _id: 67e432123504d5a7ed2156eb
    Search indexes: []

    참고

    샘플 코드가 movies 컬렉션 에 대한 인덱스 생성하지 않았으므로 결과에는 인덱스가 포함되지 않습니다.

자세한 학습 은 연결을 참조하세요.

  1. PyMongo에서 MongoClient를 가져옵니다.

    실행 중인 MongoDB 인스턴스에 연결하려면 PyMongo에 MongoClient가 필요합니다. 터미널에서 실행 중인 Python Shell에서 다음 명령을 실행하여 MongoClient를 가져옵니다.

    from pymongo import MongoClient
  2. .py 파일 에서 연결 설정을 정의합니다.

    다음 코드를 connect.py 파일 에 복사합니다.

    1from pymongo import MongoClient, errors
    2
    3# Replace '<connection-string>' with your actual MongoDB connection string
    4connection_string = '<CONNECTION-STRING>'
    5
    6# Connect to MongoDB
    7try:
    8 client = MongoClient(connection_string)
    9 print("Successfully connected to MongoDB.")
    10except errors.ConnectionError as e:
    11 print("Failed to connect to MongoDB:", e)
    12 exit()
    13
    14# Access the database and collection
    15database = client["test"]
    16collection = database["movies"]
    17
    18# Insert a document into the collection
    19try:
    20 result = collection.insert_one({"title": "Back to the Future"})
    21 print(f"Document inserted with _id: {result.inserted_id}")
    22except Exception as e:
    23 print("Failed to insert document:", e)
    24
    25# List search indexes for the collection (ensure method exists)
    26try:
    27 cursor = collection.list_search_indexes()
    28 indexes = list(cursor) # Convert cursor to list for ease
    29 if indexes:
    30 print("Search indexes found:")
    31 for index in indexes:
    32 print(index)
    33 else:
    34 print("No search indexes found.")
    35except Exception as e:
    36 print("Failed to list search indexes:", e)
    37
    38# Close the client connection (Optionally used here for resource management)
    39client.close()
  3. 자리 표시자(4줄)를 연결 문자열 로 바꾸고 파일 을 저장합니다.

  4. 다음 명령을 사용하여 샘플 애플리케이션 실행합니다.

    python connect.py
    Successfully connected to MongoDB.
    Document inserted with _id: 67e43400bd92a83c1a81cbb4
    No search indexes found.

    참고

    샘플 코드가 movies 컬렉션 에 대한 인덱스 생성하지 않았으므로 결과에는 인덱스가 포함되지 않습니다.

자세한 내용은 MongoDB에 연결을 참조하세요.

이제 복제본 세트에 연결되었으므로 MongoDB Search Community Edition으로 쿼리를 진행합니다.

이 페이지의 내용