# MongoDB connection

## Connection strings

To access a MongoDB instance, you need a **connection string**. Depending on your MongoDB deployment which can be either a *Standalone*, a *Replica Set* or a *Shared Cluster,* the connection string must be set accordingly.

The generic format for a MongoDB connection string is:

```csharp
mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
```

### Standalone deployment

For a local standalone instance that doesn't require users to identify themselves, use the following connection string:

```csharp
mongodb://localhost:27017
```

If [access control](https://docs.mongodb.com/manual/tutorial/enable-authentication/) is enabled then the connection string should contain the user's **username** and **password** and optionally the database associated with the user's credentials. The latter can be set using the [authSource](https://docs.mongodb.com/manual/reference/connection-string/#urioption.authSource) options parameter.

```csharp
mongodb://chsakell:myPassword@mongodb0.example.com:27017/?authSource=persons
```

The above connection string will try to authenticate user *chsakell* with password *myPassword* against the *persons* database.

## MongoClient

The easiest way to connect to a MongoDB standalone instance via C# is to create an instance of `MongoClient`and pass the connection string to it's constructor:

{% tabs %}
{% tab title="MongoClient" %}

```csharp
// Create a mongodb client
var client = new MongoClient(DefaultConnectionString);

public static string DefaultConnectionString = 
  Program.Configuration.GetConnectionString("MongoDBConnection");
```

{% endtab %}

{% tab title="appsettings.json" %}

```javascript
{
    "ConnectionStrings": {
        "MongoDBConnection": "mongodb://localhost:27017"
     }
}
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://chsakell.gitbook.io/mongodb-csharp-docs/getting-started/quick-start/mongodb-connection-string.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
