预计完成时间:5 分钟
要使用MongoDB Search Community Edition,您必须连接到MongoDB Community部署。使用以下方法连接到MongoDB Community部署:
MongoDB Shell 是 MongoDB 的交互式命令行界面。
MongoDB Compass,MongoDB 数据的 GUI。
一个 MongoDB 驱动程序。要查看所有可用语言,请参阅MongoDB驱动程序文档。
➤ 使用选择语言下拉菜单为此页面上的过程设立客户端。
先决条件
在开始之前,您必须具备以下先决条件:
MongoDB Community和MongoDB Search Community
注意
确保
mongod和mongot进程都在运行。要连接的有效用户名和密码
如果您尚未在副本集上创建用户,请在终端中运行以下命令来创建用户:
使用
mongosh连接到副本集。mongosh 运行以下命令,在
admin数据库中创建具有searchCoordinator角色的mongotUser用户。MongoDB使用mongotUser用户通过mongod对mongot进行身份验证。use admin db.createUser( { user: "mongotUser", pwd: passwordPrompt(), roles: [ { role: "searchCoordinator", db: "admin" } ] } ) 具有
searchCoordinator角色的用户对__mdb_internal_search数据库具有readAnyDatabase特权和写入权限。重要
请勿修改
__mdb_internal_search数据库的内容。
副本集的连接字符串包括所有成员节点。 因此,您需要副本集名称以及要连接的所有副本集的主机名或IP地址和端口。
MongoDB Compass
Java Development Kit (JDK) 8 或更高版本
我们建议使用 IntelliJ IDEA 或 Eclipse IDE 等集成开发环境 (IDE) 来配置依赖关系。
要配置 Maven 或 Gradle 以构建和运行项目,请参阅将 MongoDB 添加为依赖关系。
一个终端
一款文本编辑器
要下载适用于您的操作系统的最新版本的Python ,请参阅Python下载量页面。
pip包安装程序
从Python 2.7.9 和Python 3.4 开始,从https://python.org 下载的软件包包含
pip。要手动安装
pip,请参阅pip 安装页面。此包包含Python。
连接到副本集
使用副本集的连接字符串,通过首选客户端端连接到副本集。为确保正确配置 mongot 和 mongod,您可以运行检索搜索索引的命令。
验证与搜索实例的连接。
要进行验证,请执行以下步骤:
将文档添加到名为
movies的集合中。db.movies.insertOne({"title": "Back to the Future"}) { acknowledged: true, insertedId: ObjectId('67e42132a1cd6f443d5337b1') } 检索
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集合创建任何索引。
要学习;了解更多信息,请参阅连接到部署。
要了解更多信息,请参阅连接到 MongoDB。
以下示例应用程序使用连接字符串连接到副本集,并发送网络探测(ping)以确认连接成功。 要测试示例应用程序,请执行以下步骤:
创建一个名为
connect的新目录,并使用dotnet new命令初始化项目。mkdir connect cd connect dotnet new console 运行以下命令将 .NET/C# 驱动程序作为依赖项添加到项目中:
dotnet add package MongoDB.Driver 在
Program.cs文件中定义连接设置。将
Program.cs文件的内容替换为以下代码。示例代码执行以下操作:连接到本地部署。
在
test数据库中插入一个名为movies的集合,其中包含一个文档。检索集合的所有搜索索引。
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 4 public 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 } 将占位符(第 7 行)替换为连接字符串,然后保存文件。
运行您的应用程序。
dotnet run Program.cs Successfully connected to MongoDB. Document inserted successfully. No indexes found on the collection. 注意
结果不包含任何索引,因为示例代码没有为
movies集合创建任何索引。
要了解详细信息,请参阅连接选项。
以下示例应用程序使用连接字符串连接到副本集,并发送网络探测(ping)以确认连接成功。 通过以下步骤测试示例应用程序:
创建一个名为
connect的新目录,并使用go mod命令初始化项目。mkdir connect cd connect go mod init connect 在
.go文件中定义连接设置。在您的项目中,创建一个名为
connect.go的新文件并粘贴以下代码。1 package main 2 3 import ( 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 15 type Movie struct { 16 Title string `bson:"title"` 17 } 18 19 func 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 } 将占位符(第 15 行)替换为连接字符串,然后保存文件。
运行您的应用程序。
go run connect.go Successfully connected to MongoDB Inserted document ID: ObjectID("67e42df345bc0b636fe340f0") Search indexes found: null 注意
结果不包含任何索引,因为示例代码没有为
movies集合创建任何索引。
要学习;了解更多信息,请参阅连接。
以下示例应用程序使用连接字符串连接到副本集。 要测试示例应用程序,请执行以下步骤:
在Java类文件中定义连接设置。
将以下代码复制到名为
Connect.java的文件中。1 import com.mongodb.ConnectionString; 2 import com.mongodb.MongoClientSettings; 3 import com.mongodb.MongoException; 4 import com.mongodb.ServerApi; 5 import com.mongodb.ServerApiVersion; 6 import com.mongodb.client.MongoClient; 7 import com.mongodb.client.MongoClients; 8 import com.mongodb.client.MongoCollection; 9 import com.mongodb.client.MongoCursor; 10 import com.mongodb.client.MongoDatabase; 11 import org.bson.BsonDocument; 12 import org.bson.BsonInt64; 13 import org.bson.Document; 14 import org.bson.conversions.Bson; 15 16 public 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 } 将占位符(第 14 行)替换为连接字符串,然后保存文件。
使用 IDE 或以下命令编译并运行
Connect.java文件:javac Connect.java java Connect Successfully connected to Replica Set Document inserted successfully. Search indexes found: 注意
结果不包含任何索引,因为示例代码没有为
movies集合创建任何索引。
要了解更多信息,请参阅连接到 MongoDB。
以下示例应用程序使用连接字符串连接到副本集并返回确认消息。 要测试示例应用程序,请执行以下步骤:
在
.js文件中定义连接设置。将以下代码复制到名为
connect.js的文件中。1 const { MongoClient } = require("mongodb"); 2 3 const url = "<CONNECTION-STRING>"; 4 5 // Connect to your Replica Set 6 const client = new MongoClient(url); 7 8 async 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 30 run().catch(console.dir); 将占位符(第 4 行)替换为连接字符串,然后保存文件。
使用以下命令运行示例应用程序:
node connect.js Successfully connected to Replica Set Document inserted with _id: 67e432123504d5a7ed2156eb Search indexes: [] 注意
结果不包含任何索引,因为示例代码没有为
movies集合创建任何索引。
要学习;了解更多信息,请参阅连接。
从 PyMongo 导入 MongoClient。
要连接到正在运行的 MongoDB 实例,PyMongo 需要
MongoClient。在终端中运行的 Python shell 中,运行以下命令来导入MongoClient:from pymongo import MongoClient 在
.py文件中定义连接设置。将以下代码复制到名为
connect.py的文件中。1 from pymongo import MongoClient, errors 2 3 # Replace '<connection-string>' with your actual MongoDB connection string 4 connection_string = '<CONNECTION-STRING>' 5 6 # Connect to MongoDB 7 try: 8 client = MongoClient(connection_string) 9 print("Successfully connected to MongoDB.") 10 except errors.ConnectionError as e: 11 print("Failed to connect to MongoDB:", e) 12 exit() 13 14 # Access the database and collection 15 database = client["test"] 16 collection = database["movies"] 17 18 # Insert a document into the collection 19 try: 20 result = collection.insert_one({"title": "Back to the Future"}) 21 print(f"Document inserted with _id: {result.inserted_id}") 22 except Exception as e: 23 print("Failed to insert document:", e) 24 25 # List search indexes for the collection (ensure method exists) 26 try: 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.") 35 except Exception as e: 36 print("Failed to list search indexes:", e) 37 38 # Close the client connection (Optionally used here for resource management) 39 client.close() 将占位符(第 4 行)替换为连接字符串,然后保存文件。
使用以下命令运行示例应用程序。
python connect.py Successfully connected to MongoDB. Document inserted with _id: 67e43400bd92a83c1a81cbb4 No search indexes found. 注意
结果不包含任何索引,因为示例代码没有为
movies集合创建任何索引。
要了解更多信息,请参阅连接到 MongoDB。
后续步骤
现在您已连接到副本集,请继续使用MongoDB Search Community Edition进行查询。