MongoDB C # basic driver usage
The official MongoDB C # driver can be obtained through this link. Link to the. msiand. Zip methods to obtain the driver dll file.
This article introduces the basic database connection of the C # driver and adds, deletes, modifies, and queries operations.
When using the C # Driver, add references for "MongoDB. Bson. dll" and "MongoDB. Driver. dll" to the project. Add the following two using statements to the code.
using MongoDB.Bson;using MongoDB.Driver;
Database Connection
To establish a database connection, you must know the server address, port, and other information. All of this information is represented by a connection string. The connection string format of MongoDB is as follows:
mongodb://[username:password@]host1[:port1][,host2[:port2],…[,hostN[:portN]]][/[database][?options]]
The following describes the meaning of each field in the connection string:
- Mongodb: //: the prefix of the MongoDB connection string
- Username: password (Optional): Optional, indicating the login user name and password, used to complete user security verification
- HostN: You must specify at least one host to connect to the MongoDB instance.
- PortN (Optional): Optional. It is connected to 27017 by default.
- Database (Optional): If you specify username: password @, connect and verify that you log on to the specified database. If this parameter is not specified, the admin database is enabled by default.
- Options (Optional): Optional. If/database is not used, add /. All connection options are key-value pairs name = value. Key-value pairs are separated by & or; (semicolon ).
Here, using the example in the article "MongoDB Management", test1 and test2 have their own users. When using the following connection string for access, you can get the correct verification, because "Will1: Will1" has read and write permissions on test1. If you change to access the test2 database, an error message "Invalid credentials for database 'test2'" is returned.
string connectionStr = "mongodb://Will1:Will1@localhost";MongoClient client = new MongoClient(connectionStr);MongoServer server = client.GetServer();MongoDatabase db = server.GetDatabase("test2");MongoCollection<BsonDocument> collection = db.GetCollection("student");try{ Console.WriteLine("db name is: " + db.Name); Console.WriteLine("collections name is: " + collection.Name); Console.WriteLine("{0} items in this collection", collection.Count());}catch (Exception e){ Console.WriteLine(e.Message);}
From the code above, we can see that:
- How to obtain client and server objects
string connectionStr = "mongodb://Will1:Will1@localhost";MongoClient client = new MongoClient(connectionStr);MongoServer server = client.GetServer();
- How to obtain database and collection objects
MongoDatabase db = server.GetDatabase("test2");MongoCollection<BsonDocument> collection = db.GetCollection("student");
BsonDocument Object Model
Before you start adding, deleting, modifying, and querying, You need to introduce the BsonDocument object model.
In MongoDB collection, each document can be considered as a Bson (Binary JSON) object. Therefore, there is a BsonDocument type in the driver. You can generate a document in the following way, add a key/Value Pair using the Add method. The BsonDocument object generated in this way can be directly inserted into the collection.
BsonDocument student1 = new BsonDocument();student1.Add("sid", 10);student1.Add("name", "Will10");student1.Add("gender", "Male");student1.Add("age", 26);
In MongoDB, you can perform collection operations in two ways:
- Using the BsonDocument Object Model
- Use custom types
We have already introduced the BsonDocument object. Here we can also use our own custom type. For example, we can define a Student type to insert objects of this type into the collection.
public class Student{ public ObjectId _id; public int sid; public string name; public string gender; public int age;}
Note: When using a custom type, you must have an Id field.
Both of the above methods can be used, and each method has its own advantages. Using a custom type method, you can make the documents in the collection have a unified mode; the BsonDocument method supports more document modes. That is to say, if the document in a collection has various modes, the BsonDocument method is more flexible.
Insert data
For data insertion, we can use the "Insert ()" method in the collection. Two records are inserted below. You can use the BsonDocument object method or the custom type method to insert data.
By using BsonDocument, you can define the document format freely. For example, a "holobby" field is added (Ps: This is not recommended, which will cause trouble in document query ).
BsonDocument student1 = new BsonDocument();student1.Add("sid", 10);student1.Add("name", "Will10");student1.Add("gender", "Male");student1.Add("age", 26);student1.Add("hobby", new BsonArray() { "swimming","reading"});collection.Insert(student1);Student student2 = new Student();student2.age = 27;student2.name = "Wilber";student2.gender = "Male";collection.Insert(student2);
Query data
MongoDB driver supports three query methods.
QueryDocument
This method is similar to the conditional query in MongoDB shell. For example, query students older than 20
QueryDocument queryDocument = new QueryDocument("age", new QueryDocument("$gt",20));foreach (var student in collection.Find(queryDocument)){ Console.WriteLine(student);}
When there are multiple query conditions, for example, query for male students older than 20
QueryDocument queryDocument = new QueryDocument(new BsonElement("age", new QueryDocument("$gt", 20)), new BsonElement("gender","Male"));
Query Builder
Query Builder is a more concise method. When querying in this way, we need to use the builder in the driver to generate a query. Therefore, the following using statement must be referenced.
using MongoDB.Driver.Builders;
The following statement can be used to query students older than 20
var query = Query.GT("age", 20); foreach (var student in collection.Find(query)) { Console.WriteLine(student); }
Query male students older than 20
var query = Query.And(Query.GT("age", 20), Query.EQ("gender", "Male"));
Of course, we can also perform a strong-type query, but this query requires that "the fields in this document must be a subset of custom-type fields, that is, the document can be converted to a specific type ". For example, we have inserted a document with the "holobby" key. If the following method is used, an exception will occur, prompting that the Student type does not contain the holobby field.
var query = Query<Student>.GT(e => e.age, 20);foreach (var student in collection.FindAs<Student>(query)){ Console.WriteLine(student);}
In this case, you can use the BsonDocument type for queries. One thing I don't understand is why the Student type does not report an error.
var query = Query<Student>.GT(e => e.age, 20);foreach (var student in collection.FindAs<BsonDocument>(query)){ Console.WriteLine(student);}
Supports
After the driver's 1.8 release, the official driver can support the LINQ operation. We only need to use the following using statement to support the query in the LINQ mode.
using MongoDB.Driver.Linq;
Therefore, you can query students older than 20, or use the following method (note that all documents can be converted to Student type)
var linquery = from e in collection.AsQueryable<Student>() where e.age > 20 select e;var linquery1 = collection.AsQueryable<Student>().Where(e => e.age > 20);
The MongoDB documentation contains many LINQ query operations. For details, refer to the section "LINQ" in the MongoDB documentation.
Update Data
There are two methods to Update a document. You can use the Save method to replace the entire document or use the Update method to partially Update the document.
For example, find the document with sid 9 and name Will9 and update the age field to 27.
Save Method
var query = Query.And(Query.EQ("sid", 9), Query.EQ("name", "Will9"));BsonDocument Will9 = collection.FindOne(query);if (Will9 != null){ Will9["age"] = 27; collection.Save(Will9);}
Update Method
var query = Query.And(Query.EQ("sid", 9), Query.EQ("name", "Will9"));var update = Update.Set("age", 27);collection.Update(query, update);
Delete data
Deleting data is relatively simple.
Delete a document with a specific condition:
var query = Query.EQ("sid", 9);collection.Remove(query);
Delete all documents:
collection.RemoveAll();
Summary
This article describes the basic operations of MongoDB's official C # driver.
Among the three Query methods, Query Builder is the most flexible. It is recommended that all documents have a unified mode for queries using the LINQ method, so that custom types can be conveniently used.
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: