Connect to MongoDB Search Community
For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt
Connect to MongoDB Search Community
Estimated completion time: 5 minutes
To use MongoDB Search and Vector Search in Community, 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, a GUI for your MongoDB data.
-
A MongoDB driver. To see all available languages, refer to the MongoDB Driver documentation.
Use the drop-down menus to select the interface and languages, when applicable, for the procedure on this page.
Prerequisites
Before you start, you must have the following prerequisites:
- [MongoDB Community](https://www.mongodb.com/docs/manual/administration/install-community.md#std-label-install-mdb-community-edition and [MongoDB Search Community](https://www.mongodb.com/docs/search/self-managed/current/installation/linux.md#std-label-community-search-deploy
Note:
Make sure that both the mongod and mongot processes are running.
- 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:
Connect to replica set by using mongosh.
shell
mongosh
Run the following commands to create a mongotUser user in the admin database with the [searchCoordinator](https://www.mongodb.com/docs/manual/reference/built-in-roles.md#mongodb-authrole-searchCoordinator role. MongoDB uses the mongotUser user to authenticate mongot with mongod.
javascript
use admin
db.createUser( {
user: "mongotUser",
pwd: passwordPrompt(),
roles: [ { role: "searchCoordinator", db: "admin" } ]
} )
Users with the searchCoordinator role have [readAnyDatabase](https://www.mongodb.com/docs/manual/reference/built-in-roles.md#mongodb-authrole-readAnyDatabase privileges and write permissions on the __mdb_internal_search database.
Important:
Do not modify the contents of the __mdb_internal_search database.
- [Connection string to the replica set](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri
The connection string for a replica set includes all member nodes. Therefore, you need the replica set name and the hostnames or IP addresses and ports of all the replica set members to connect.
-
[
mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh -
A terminal
-
A text editor
-
A C# project
To initialize a project, run the dotnet new
console command in your project directory. To learn more, see C# Quick Start.
-
A terminal
-
A text editor
-
A Go project
To initialize a project, use the go mod command. To learn more, see Go Quick Start.
- MongoDB Go driver
To download and install the Go driver and driver dependencies, run the following commands:
shell
go get go.mongodb.org/mongo-driver/v2/mongo
go get github.com/joho/godotenv
-
Java Development Kit (JDK) version 8 or later
We recommend using an integrated development environment (IDE) such as IntelliJ IDEA or Eclipse IDE to configure the dependencies.
To configure Maven or Gradle to build and run your project, see [Add MongoDB as a Dependency.](https://www.mongodb.com/docs/drivers/java/sync/current/quick-start/#add-mongodb-as-a-dependency
To install the Node.js driver, run the following command at a terminal prompt:
npm install mongodb --save
-
A terminal
-
A text editor
To download the latest version of Python for your operating system, see Python Downloads Page.
- The pip package installer
Starting with Python 2.7.9 and Python 3.4, packages downloaded from https://python.org include pip.
To install pip manually, see the pip installation page. This package includes Python.
Connect to Your Replica Set
Use your replica set's [connection string](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri 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.
-
Open a terminal.
-
Paste and run the command to connect in your terminal.
For example, run a command similar to the following to connect after replacing the placeholder values in the command:
shell
mongosh -u <USER-NAME> -p <USER-PASSWORD> --authenticationDatabase "<AUTHENTICATION-DB>" --host <HOST-NAME> --port <PORT-NUMBER>
You should now be connected to your replica set and your terminal should display something similar to the following:
none
rs0 [direct: primary] test>
- Verify your connection to the search instance.
To verify, perform the following steps:
Add a document to a collection named movies.
json
db.movies.insertOne({"title": "Back to the Future"})
Output:
javascript
{
acknowledged: true,
insertedId: ObjectId('67e42132a1cd6f443d5337b1')
}
Retrieve all search indexes for the movies collection.
json
db.runCommand({"listSearchIndexes": "movies"});
Output:
javascript
{
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 })
}
Note:
The results don't contain any indexes because the sample code didn't create any index for the movies collection.
To learn more, see Connect to a Deployment.
-
Open MongoDB Compass and click Add new connection.
-
Paste your connection string and connect to replica set.
To learn more, see Connect to MongoDB.
The following sample application connects to your replica set with your connection string and sends a ping to confirm a successful connection. To test the sample application, perform the following steps:
Create a new directory called connect and initialize your project by using the dotnet new command.
mkdir connect
cd connect
dotnet new console
Run the following command to add the .NET/C# driver to your project as a dependency:
dotnet add package MongoDB.Driver
Define your connection settings in the Program.cs file.
Replace the contents of the Program.cs file with the following code. The sample code does the following:
-
Connects to your local deployment.
-
Inserts a collection named
movieswith one document in thetestdatabase. -
Retrieves all search indexes for the collection.
using MongoDB.Bson;
using MongoDB.Driver;
public class Connect
{
// Replace the following with your connection string
private const string MongoConnectionString = "<CONNECTION-STRING>";
public static void Main(string[] args)
{
// Connect to your replica set
var client = new MongoClient(MongoConnectionString);
// Send a ping to confirm a successful connection
try {
var result = client.GetDatabase("admin").RunCommand<BsonDocument>(new BsonDocument("ping", 1));
Console.WriteLine("Successfully connected to Replica Set");
}
catch (Exception e) { Console.WriteLine(e);}
// Insert a document to a collection
var database = client.GetDatabase("test");
var collection = database.GetCollection<BsonDocument>("movies");
var movieDocument = new BsonDocument{{"title", "Back to the Future"}};
try {
collection.InsertOne(movieDocument);
Console.WriteLine("Document inserted successfully.");
}
catch (Exception e) {
Console.WriteLine($"Insertion error: {e.Message}");
}
// List search indexes
try {
var indexes = collection.SearchIndexes.List().ToList();
if (indexes.Count == 0) {
Console.WriteLine("No indexes found on the collection.");
}
else {
Console.WriteLine("Indexes on the collection:");
foreach (var index in indexes)
{
Console.WriteLine(index.ToJson());
}
}
}
catch (Exception e) {
Console.WriteLine($"Error listing indexes: {e.Message}");
}
}
}
Replace the placeholder (line 7) with your connection string and save the file.
Run your application.
dotnet run Program.cs
Output:
Successfully connected to MongoDB.
Document inserted successfully.
No indexes found on the collection.
Note:
The results don't contain any indexes because the sample code didn't create any index for the movies collection.
To learn more, see Connection Options.
The following sample application connects to your replica set with your connection string and sends a ping to confirm a successful connection. Test the sample application with the following steps:
Create a new directory called connect and initialize your project by using the go mod command.
mkdir connect
cd connect
go mod init connect
Define your connection settings in a .go file.
In your project, create a new file called connect.go and paste the following code.
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
type Movie struct {
Title string `bson:"title"`
}
func main() {
// Replace with your connection string
uri := "<CONNECTION-STRING>"
// Connect to MongoDB
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
if err != nil {
log.Fatalf("Failed to connect to MongoDB: %v", err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
log.Fatalf("Failed to disconnect MongoDB client: %v", err)
}
}()
// Ping to confirm connection
if err := client.Ping(context.TODO(), readpref.Primary()); err != nil {
log.Fatalf("Failed to ping MongoDB: %v", err)
}
fmt.Println("Successfully connected to MongoDB")
// Insert a document to a collection
coll := client.Database("test").Collection("movies")
newMovie := Movie{Title: "Back to the Future"}
result, err := coll.InsertOne(context.TODO(), newMovie)
if err != nil {
log.Fatalf("Failed to insert document: %v", err)
}
fmt.Printf("Inserted document ID: %v\n", result.InsertedID)
// List search indexes
listOpts := options.ListSearchIndexesOptions{}
ctx := context.TODO()
cursor, err := coll.SearchIndexes().List(ctx, nil, &listOpts)
if err != nil {
log.Fatalf("Failed to list search indexes: %v", err)
}
var results []bson.D
if err = cursor.All(ctx, &results); err != nil {
log.Fatalf("Failed to iterate over cursor: %v", err)
}
res, err := json.Marshal(results)
if err != nil {
log.Fatalf("Failed to marshal results to JSON: %v", err)
}
fmt.Println("Search indexes found:", string(res))
}
Replace the placeholder (line 15) with your connection string and save the file.
Run your application.
go run connect.go
Output:
Successfully connected to MongoDB
Inserted document ID: ObjectID("67e42df345bc0b636fe340f0")
Search indexes found: null
Note:
The results don't contain any indexes because the sample code didn't create any index for the movies collection.
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:
Define your connection settings in a Java class file.
Copy the following code into a file called Connect.java.
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoException;
import com.mongodb.ServerApi;
import com.mongodb.ServerApiVersion;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.BsonDocument;
import org.bson.BsonInt64;
import org.bson.Document;
import org.bson.conversions.Bson;
public class Connect {
public static void main(String[] args) {
// Replace the placeholder with your Replica Set connection string
String uri = "<CONNECTION-STRING>";
// Construct a ServerApi instance using the ServerApi.builder() method
ServerApi serverApi = ServerApi.builder()
.version(ServerApiVersion.V1)
.build();
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(uri))
.serverApi(serverApi)
.build();
// Create a new client and connect to the server
try (MongoClient mongoClient = MongoClients.create(settings)) {
MongoDatabase adminDatabase = mongoClient.getDatabase("admin");
try {
// Send a ping to confirm a successful connection
Bson command = new BsonDocument("ping", new BsonInt64(1));
adminDatabase.runCommand(command);
System.out.println("Successfully connected to Replica Set");
} catch (MongoException e) {
System.err.println("Ping failed: " + e);
}
// Insert a document into a collection
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("movies");
Document movieDocument = new Document("title", "Back to the Future");
try {
collection.insertOne(movieDocument);
System.out.println("Document inserted successfully.");
} catch (MongoException e) {
System.err.println("Insertion failed: " + e);
}
// List search indexes
try (MongoCursor<Document> resultsCursor = collection.listSearchIndexes().iterator()) {
System.out.println("Search indexes found:");
while (resultsCursor.hasNext()) {
System.out.println(resultsCursor.next().toJson());
}
} catch (MongoException e) {
System.err.println("Error listing indexes: " + e);
}
} catch (MongoException e) {
System.err.println("Failed to create MongoClient: " + e);
}
}
}
Replace the placeholder (line 14) with your connection string and save the file.
Compile and run the Connect.java file by using an IDE or the following commands:
javac Connect.java
java Connect
Output:
Successfully connected to Replica Set
Document inserted successfully.
Search indexes found:
Note:
The results don't contain any indexes because the sample code didn't create any index for the movies collection.
To learn more, see Connect to MongoDB.
The following sample application connects to your replica set with your connection string and returns a confirmation message. To test the sample application, perform the following steps:
Define your connection settings in a .js file.
Copy the following code into a file called connect.js.
const { MongoClient } = require("mongodb");
const url = "<CONNECTION-STRING>";
// Connect to your Replica Set
const client = new MongoClient(url);
async function run() {
try {
await client.connect();
console.log("Successfully connected to Replica Set");
// Insert a document in a collection
const database = client.db("test");
const coll = database.collection("movies");
const doc = { title: "Back to the Future" };
const insertResult = await coll.insertOne(doc);
console.log(`Document inserted with _id: ${insertResult.insertedId}`);
// List search indexes for the collection
const searchIndexesResult = await coll.listSearchIndexes().toArray();
console.log("Search indexes:", searchIndexesResult);
} catch (err) {
console.log("Error occurred:", err.stack);
} finally {
await client.close();
}
}
run().catch(console.dir);
Replace the placeholder (line 4) with your connection string and save the file.
Run the sample application using the following command:
node connect.js
Output:
Successfully connected to Replica Set
Document inserted with _id: 67e432123504d5a7ed2156eb
Search indexes: []
Note:
The results don't contain any indexes because the sample code didn't create any index for the movies collection.
To learn more, see Connection.
Import MongoClient from PyMongo.
To connect to a running MongoDB instance, PyMongo requires MongoClient. In the Python shell running in your terminal, run the following command to import MongoClient:
from pymongo import MongoClient
Define your connection settings in a .py file.
Copy the following code to a file named connect.py.
from pymongo import MongoClient, errors
## Replace '<connection-string>' with your actual MongoDB connection string
connection_string = '<CONNECTION-STRING>'
## Connect to MongoDB
try:
client = MongoClient(connection_string)
print("Successfully connected to MongoDB.")
except errors.ConnectionError as e:
print("Failed to connect to MongoDB:", e)
exit()
## Access the database and collection
database = client["test"]
collection = database["movies"]
## Insert a document into the collection
try:
result = collection.insert_one({"title": "Back to the Future"})
print(f"Document inserted with _id: {result.inserted_id}")
except Exception as e:
print("Failed to insert document:", e)
## List search indexes for the collection (ensure method exists)
try:
cursor = collection.list_search_indexes()
indexes = list(cursor) # Convert cursor to list for ease
if indexes:
print("Search indexes found:")
for index in indexes:
print(index)
else:
print("No search indexes found.")
except Exception as e:
print("Failed to list search indexes:", e)
## Close the client connection (Optionally used here for resource management)
client.close()
Replace the placeholder (line 4) with your connection string and save the file.
Run the sample application using the following command.
python connect.py
Output:
Successfully connected to MongoDB.
Document inserted with _id: 67e43400bd92a83c1a81cbb4
No search indexes found.
Note:
The results don't contain any indexes because the sample code didn't create any index for the movies collection.
To learn more, see Connect to MongoDB.
Next Steps
Now that you've connected to your replica set, proceed to Query with MongoDB Search and Vector Search in Community.
