Using System;
Using System.Collections.Generic;
Using System.Linq;
Using MongoDB;
<summary>
Packaging classes for MONGO and Mongodatabase
</summary>
public class Mymongodb:idisposable
{
Private Mongo _mongo;
Private Imongodatabase _db;
private static string connectionString = "Server=127.0.0.1;mydb";
private static readonly string _connectionstring = Connectionstring.split (';') [0];//"server=127.0.0.1";
private static readonly string _dbname = Connectionstring.split (';') [1];
Public Mymongodb ()
: This (_connectionstring, _dbname)
{
}
Public Mymongodb (String dbName)
: This (_connectionstring, dbName)
{
}
<summary>
constructor function. Based on the specified connection string and database name
</summary>
<param name= "connectionString" > Connection string </param>
<param name= "DbName" > Database name, can be empty, but must be called Usedb () method before any operations database </param>
Public Mymongodb (String connectionString, String dbName)
{
if (string. IsNullOrEmpty (connectionString))
throw new ArgumentNullException ("connectionString");
_mongo = new MONGO (connectionString);
Connect to MongoDB Now
_mongo. Connect ();
if (string. IsNullOrEmpty (dbName) = = False)
_db = _mongo. Getdatabase (DbName);
}
<summary>
Switch to the specified database
</summary>
<param name= "DbName" ></param>
<returns></returns>
Public imongodatabase Usedb (string dbName)
{
if (string. IsNullOrEmpty (DbName))
throw new ArgumentNullException ("DbName");
_db = _mongo. Getdatabase (DbName);
return _db;
}
<summary>
Get the currently connected database
</summary>
Public Imongodatabase CurrentDb
{
Get
{
if (_db = = null)
throw new Exception ("The current connection does not specify any database.") Please specify the database name in the constructor or call the Usedb () method to switch the database. ");
return _db;
}
}
<summary>
Gets the specified collection of the current connection database "by Type"
</summary>
<typeparam name= "T" ></typeparam>
<returns></returns>
Public imongocollection<t> getcollection<t> () where T:class
{
return this. Currentdb.getcollection<t> ();
}
<summary>
Gets the specified collection of the current connection database "according to the specified name"
</summary>
<typeparam name= "T" ></typeparam>
<param name= "Name" > collection name </param>
<returns></returns>
Public imongocollection<t> getcollection<t> (string name) where T:class
{
return this. currentdb.getcollection<t> (name);
}
public void Dispose ()
{
if (_mongo! = null) {
_mongo. Dispose ();
_mongo = null;
}
}
}
Using the Encapsulation class
public void Insert (user user)
{
using (Mymongodb mdb = new Mymongodb ())
{
var collection = mdb. Getcollection<user> ();
Collection. Insert (user);
}
}
ASP. NET-link classes that encapsulate MongoDB