Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /

Connect to MongoDB Search Community

Tiempo estimado de finalización: 5 minutos

To use MongoDB Search Community Edition, you must connect to your MongoDB Community deployment. Use the following methods to connect to your MongoDB Community deployment:

  • The MongoDB Shell, an interactive command line interface to MongoDB.

  • MongoDB Compass, una interfaz gráfica de usuario para sus datos de MongoDB.

  • Un controlador de MongoDB. Para ver todos los lenguajes disponibles, consulte la Documentación del driver de MongoDB.

➤ Use the Select your language drop-down menu to set the client for the procedure on this page.

Antes de comenzar, debe tener los siguientes requisitos previos:

  • Comunidad MongoDB y Comunidad MongoDB Search

    Nota

    Asegúrate de que tanto el mongod y mongot procesos se están ejecutando.

  • Valid username and password to connect

    If you haven't already created a user on your replica set, run the following commands in your terminal to create a user:

    1. Conéctese al set de réplicas usando mongosh.

      mongosh
    2. Ejecuta los siguientes comandos para crear un usuario mongotUser en la base de datos admin con el rol de searchCoordinator. MongoDB utiliza el usuario mongotUser para autenticar mongot con mongod.

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

      Users with the searchCoordinator role have readAnyDatabase privileges and write permissions on the __mdb_internal_search database.

      Importante

      No se debe modificar el contenido de la base de datos __mdb_internal_search.

  • Cadena de conexión al set de réplicas

    La cadena de conexión para un set de réplicas incluye todos los nodos nodos. Por lo tanto, necesita el nombre del set de réplicas y los nombres de host o direcciones IP y puertos de todos los miembros del set de réplicas para conectarse.

  • MongoDB Compass

  • Un terminal

  • Un editor de texto

  • dotnet

  • Un proyecto en C#

    To initialize a project, run the dotnet new console command in your project directory. To learn more, see C# Quick Start.

  • Un terminal

  • Un editor de texto

  • Go

  • Un proyecto Go

    To initialize a project, use the go mod command. To learn more, see Go Quick Start.

  • MongoDB Go driver

    Para descargar e instalar el controlador Go y las dependencias del controlador, debes ejecutar los siguientes comandos:

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

Para instalar el Node.js Driver, ejecuta el siguiente comando en un terminal:

npm install mongodb --save

Use your replica set's connection string to connect to your replica set with your preferred client. To ensure that you configured mongot and mongod correctly, you can run a command that retrieves search indexes.

1
2

Por ejemplo, ejecútese un comando similar al siguiente para conectarse después de reemplazar los valores del marcador de posición en el comando:

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

Ahora deberías estar conectado a tu set de réplicas y tu terminal debería mostrar algo similar a lo siguiente:

rs0 [direct: primary] test>
3

Para verificar, realiza los siguientes pasos:

  1. Agrega un documento a una colección llamada movies.

    db.movies.insertOne({"title": "Back to the Future"})
    {
    acknowledged: true,
    insertedId: ObjectId('67e42132a1cd6f443d5337b1')
    }
  2. Recuperar todos los índices de búsqueda para la colección 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 })
    }

    Nota

    Los resultados no contienen ningún índice porque el código de muestra no creó ninguno para la colección movies.

To learn more, see Connect to a Deployment.

1
2

Para aprender más, consulta Conéctese a MongoDB.

La siguiente aplicación de muestra se conecta a tu conjunto de réplicas con tu cadena de conexión y envía un ping para confirmar una conexión exitosa. Para probar la aplicación de muestra, siga estos pasos:

  1. Cree un nuevo directorio llamado connect e inicialice su proyecto usando el comando dotnet new.

    mkdir connect
    cd connect
    dotnet new console
  2. Se debe ejecutar el siguiente comando para agregar el .NET/C# Driver al proyecto como dependencia:

    dotnet add package MongoDB.Driver
  3. Sus configuraciones de conexión en el archivo Program.cs.

    Replace the contents of the Program.cs file with the following code. The sample code does the following:

    • Se conecta a tu implementación local.

    • Inserta una colección denominada movies con un documento en la base de datos test.

    • Recupera todos los índices de búsqueda para la colección.

    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. Reemplace el marcador de posición (línea 7) con su cadena de conexión y guarde el archivo.

  5. Ejecuta la aplicación.

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

    Nota

    Los resultados no contienen ningún índice porque el código de muestra no creó ninguno para la colección movies.

Para obtener más información, consulta Opciones de conexión.

La siguiente aplicación de muestra se conecta a tu set de réplicas usando tu cadena de conexión y envía un ping para confirmar una conexión exitosa. Prueba la aplicación de muestra con los siguientes pasos:

  1. Cree un nuevo directorio llamado connect e inicialice su proyecto usando el comando go mod.

    mkdir connect
    cd connect
    go mod init connect
  2. Define your connection settings in a .go file.

    En el proyecto, se debe crear un archivo nuevo llamado connect.go y pegar el siguiente código.

    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. Reemplace el marcador de posición (línea 15) con su cadena de conexión y guarde el archivo.

  4. Ejecuta la aplicación.

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

    Nota

    Los resultados no contienen ningún índice porque el código de muestra no creó ninguno para la colección movies.

To learn more, see Connections.

The following sample application connects to your replica set with your connection string. To test the sample application, perform the following steps:

  1. Define tus ajustes de conexión en un archivo de clase Java.

    Copia el siguiente código en un archivo llamado 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. Reemplace el marcador de posición (línea 14) con su cadena de conexión y guarde el archivo.

  3. Compile y ejecute el archivo Connect.java utilizando un IDE o los siguientes comandos:

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

    Nota

    Los resultados no contienen ningún índice porque el código de muestra no creó ninguno para la colección movies.

Para aprender más, consulta Conéctese a MongoDB.

La siguiente aplicación de muestra se conecta a su set de réplicas con su cadena de conexión y devuelve un mensaje de confirmación. Para probar la aplicación de muestra, realice los siguientes pasos:

  1. Define your connection settings in a .js file.

    Copia el siguiente código en un archivo llamado 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. Reemplace el marcador de posición (línea 4) con su cadena de conexión y guarde el archivo.

  3. Ejecute la aplicación de muestra utilizando el siguiente comando:

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

    Nota

    Los resultados no contienen ningún índice porque el código de muestra no creó ninguno para la colección movies.

Para obtener más información, consulta Conexión.

  1. Importe MongoClient de PyMongo.

    Para conectarse a una instancia de MongoDB en ejecución, PyMongo requiere MongoClient. En el shell de Python que se ejecuta en su terminal, ejecute el siguiente comando para importar MongoClient:

    from pymongo import MongoClient
  2. Define your connection settings in a .py file.

    Copie el siguiente código en un archivo llamado 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. Reemplace el marcador de posición (línea 4) con su cadena de conexión y guarde el archivo.

  4. Run the sample application using the following command.

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

    Nota

    Los resultados no contienen ningún índice porque el código de muestra no creó ninguno para la colección movies.

Para aprender más, consulta Conéctese a MongoDB.

Ahora que se ha conectado a su set de réplicas, continúe con Query con MongoDB Search Community Edition.

En esta página