Table of Contents

Install

Install the nuget package with command:

dotnet add package MongoDB.Entities

Initialize

Import the package with using MongoDB.Entities; and initialize the database connection as follows:

Basic initialization

var db = await DB.InitAsync("DatabaseName");
Note

The first database you initializes with the DB.InitAsync call becomes the default database of the application. You can retrieve the default database from anywhere in your code with the static property DB.Default. Once databases are initialized during startup with DB.InitAsync, you can retrieve an instance of any initialized database by supplying the name of the database with DB.Instance("DatabaseName"). If you have multiple MongoClients with the same database name, you can access that instance by supplying both the database name and the client settings like so: DB.Instance("DatabaseName", clientSettings).

Advanced initialization

var db = await DB.InitAsync("DatabaseName", new MongoClientSettings()
  {
      Server = new MongoServerAddress("localhost", 27017),
      Credential = MongoCredential.CreateCredential("DatabaseName", "username", "password")
  },
  new MongoDatabaseSettings()
  {
      ReadConcern = ReadConcern.Majority,
      WriteConcern = WriteConcern.WMajority
  });

Using a connection string

var db = await DB.InitAsync("DatabaseName",
  MongoClientSettings.FromConnectionString(
    "mongodb://{username}:{password}@{hostname}:{port}/?authSource=admin"));