MongoDB C # Drivers only some classes are thread-safe, including (Mongoserver, Mongodatabase, Mongocollection, Mongogridfs), and most of the other classes are not thread-safe.
Some scenarios need to ensure that the data is correct, and a series of operations need to be bound to db-level objects. Consistency can then be ensured in a manner similar to transaction control.
Transaction control
static void Main (string[] args)
{
Database connection string
String connectionString = "mongodb://127.0.0.1:27017";
Get a connection to an object instance
var client = new Mongoclient (connectionString);
var server = client. Getserver ();
Mongoserver Server = Mongoserver.create (connectionString);
Specifying a security certificate
Mongocredentials credential = new Mongocredentials ("Wander", "123456");
Get a "MongoDB" Connection object
Mongodatabase mydb = server. Getdatabase ("Test", credential);
Start transaction control
Server. Requeststart (MyDB);
Add business logic here
End transaction control
Server. Requestdone ();
}
MongoDB instance Operations
An instance is the largest unit of work in a database, with objects such as databases, tables, and so on, followed by instance-level operations.
1) Determine if the MongoDB instance is alive
Determine if the current instance is alive
static void Main (string[] args)
{
Database connection string
String connectionString = "Mongodb://root:[email protected]:27017";
Get a connection to an object instance
var client = new Mongoclient (connectionString);
var server = client. Getserver ();
Server. Ping ();
}
No surviving will throw an exception
2) remote control to manage MongoDB instances
Close a MongoDB instance
static void Main (string[] args)
{
Database connection string
String connectionString = "Mongodb://root:[email protected]:27017";
Get a connection to an object instance
var client = new Mongoclient (connectionString);
var server = client. Getserver ();
Server. Shutdown ();
}
Notice there's no certificate? This requires the highest-level root user to connect without specifying a certificate.
3) List all the databases
static void Main (string[] args)
{
Database connection string
String connectionString = "Mongodb://root:[email protected]:27017";
Get a connection to an object instance
var client = new Mongoclient (connectionString);
var server = client. Getserver ();
var names = server. Getdatabasenames ();
foreach (var name in names)
{
Console.WriteLine (name);
}
Console.ReadLine ();
}
4) Determine if the database exists
Determine if the database exists
static void Main (string[] args)
{
Database connection string
String connectionString = "Mongodb://root:[email protected]:27017";
Get a connection to an object instance
var client = new Mongoclient (connectionString);
var server = client. Getserver ();
Console.WriteLine (server. Databaseexists ("test"));
Console.ReadLine ();
}
C # Development Interface--mongodb (for library operations)