The current version of the C# driver used by MongoDB is 1.6.0
Download address: https://github.com/mongodb/mongo-csharp-driver/downloads
1, Connect to database
The code is as follows:
private const string cOnn= “mongodb://127.0.0.1:27017”;
string dbName = “mongodb_name”;
//Create a data connection
MongoServer server = MongoServer.Create(conn); col = db.GetCollection(tbName);
2. Insert data
Because MongoDB does not have the concept of a table, you must define your own data model before inserting data
User.cs
The following is the code for adding data
The code is as follows:
// Content
/// Article ID
/// Channel ID
///
public static void Add(User t)
{
//Create data connection
MongoServer server = MongoServer.Create (conn);
//Get the specified database
Insert
col.Insert(t);
}
3. Delete operation
The code is as follows:
> ///
public static void Delete(string objId)
; /P>
IMongoQuery query = Query.EQ(“_id”, new ObjectId(objId));
col.Remove(query);
. Summary>
/// Modify according to ObjectID
///
public static void Update(User t)
{
//Create data connection
MongoServer server = MongoServer.Create(conn);
//Get the specified database
MongoDatabase db = server .GetDatabase(dbName);
//Get the table
BsonDocument bd = BsonExtensionMethods.ToBsonDocument(t);
IMongoQuery query = Query.EQ(“_id”, t.Id);
col.Update(query, new UpdateDocument(bd));
}
5. Conditional query (simple)
The code is as follows:
> Public static TuCao SelectOne(string objId)
{
//Create a data connection
MongoServer server = MongoServer.Create(conn);
//Get the specified database
b = server. GetDatabase(dbName);
//Get the table
MongoCollection col = db.GetCollection(tbName);
//Conditional query Return col.FindOne(Query.EQ( “_id”, new ObjectId(objId)));
}
6. Query all
The code is as follows:
public static void SelectAll()
{
List list = new List();
MongoServer server = Br> Mongocollection Col = db.getCollection (tbname);
// Query all
List.addrage (colorFindall ());
//——————————–
foreach (TuCao t in col.FindAll() 🙂 }
}