|
Want to use MongoDB in C #, you must first have a MongoDB supports C # version of the driver. C # version of the driver there are many, such as provided by the official, samus. Realization of ideas most similar. Here we will start with the official mongo-csharp-driver, the current version is 1.7.0.4714
download link:
http://github.com/mongodb/mongo-csharp-driver/downloads
Get two dll after compiling
MongoDB.Driver.dll: As the name suggests, the driver
MongoDB.Bson.dll: serialization, Json related
Then reference these two dll in our program.
The following section briefly demonstrates how to use C # for MongoDB CRUD operations.
Program.cs
using System;
using MongoDB.Driver;
using MongoDB.Bson;
namespace ConsoleApplication1
{
class Program
{
static void Main (string [] args)
{
// Database connection string
string conn = "mongodb: //127.0.0.1: 27017";
// Database name
string database = "RsdfDb";
string collection = "Act_User";
MongoServer mongodb = MongoServer.Create (conn); // connect to the database
MongoDatabase mongoDataBase = mongodb.GetDatabase (database); // Select the database name
MongoCollection mongoCollection = mongoDataBase.GetCollection (collection); // select the collection, the equivalent of table
mongodb.Connect ();
// Insert common
var o = new {UserID = 0, UserName = "admin", Password = "1"};
mongoCollection.Insert (o);
// Insert objects
User user = new User {UserID = 1, UserName = "chenqp", Password = "1"};
mongoCollection.Insert (user);
// BsonDocument insert
BsonDocument bd = new BsonDocument ();
bd.Add ( "UserID", 2);
bd.Add ( "UserName", "yangh");
bd.Add ( "Password", "1");
mongoCollection.Insert (bd);
Console.ReadLine ();
}
}
}
User.cs
using MongoDB.Bson;
namespace ConsoleApplication1
{
class User
{
// _ Id attribute must be, otherwise the update data being given: "Element '_id' does not match any field or property of class".
public ObjectId _id; //BsonType.ObjectId this corresponds MongoDB.Bson.ObjectId
public int UserID {get; set;}
public string UserName {get; set;}
public string Password {get; set;}
}
} |
|
|
|