Use MongoDB C # official driver to operate MongoDB
To use MongoDB in C #, you must first have a C # drive supported by MongoDB. C # has many types of drivers, such as samus. Most of the Implementation ideas are similar. Here we first use the official mongo-csharp-driver. The current version is 1.7.0.4714.
:
Http://github.com/mongodb/mongo-csharp-driver/downloads
After compilation, two dll files are obtained.
MongoDB. Driver. dll: as the name suggests, the Driver
MongoDB. Bson. dll: serialization, Json-related
Then reference the two dll files in our program.
The following section briefly demonstrates how to use C # to add, delete, modify, and query MongoDB.
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: // FIG: 27017 ";
// Database Name
String database = "RsdfDb ";
String collection = "Act_User ";
Login Server mongodb = Login server. Create (conn); // connect to the database
Repeated database connected database = mongodb. GetDatabase (database); // select the database Name
Collections collection collections collection = collections database. GetCollection (collection); // select a collection, which is equivalent to a table
Mongodb. Connect ();
// Normal insert
Var o = new {UserID = 0, UserName = "admin", Password = "1 "};
Collections collection. Insert (o );
// Insert an object
User user = new User {UserID = 1, UserName = "chenqp", Password = "1 "};
Collections collection. Insert (user );
// Insert BsonDocument
BsonDocument bd = new BsonDocument ();
Bd. Add ("UserID", 2 );
Bd. Add ("UserName", "yangh ");
Bd. Add ("Password", "1 ");
Collections collection. Insert (bd );
Console. ReadLine ();
}
}
}
User. cs
Using MongoDB. Bson;
Namespace ConsoleApplication1
{
Class User
{
// The _ id attribute must be available; otherwise, an error occurs when updating data: "Element '_ id' does not match any field or property of class ".
Public ObjectId _ id; // BsonType. ObjectId corresponds to MongoDB. Bson. ObjectId
Public int UserID {get; set ;}
Public string UserName {get; set ;}
Public string Password {get; set ;}
}
}
The shell interface is as follows:
For more MongoDB tutorials, see the following:
CentOS compilation and installation of php extensions for MongoDB and mongoDB
CentOS 6 install MongoDB and server configuration using yum
Install MongoDB2.4.3 in Ubuntu 13.04
MongoDB beginners must read (both concepts and practices)
MongoDB Installation Guide for Ubunu 14.04
MongoDB authoritative Guide (The Definitive Guide) in English [PDF]
Nagios monitoring MongoDB sharded cluster service practice
Build MongoDB Service Based on CentOS 6.5 Operating System
MongoDB details: click here
MongoDB: click here
This article permanently updates the link address: