Download driver
There are two ways to download a driver: One is to install through NuGet in a C # project, and the other is via the following link: https://github.com/mongodb/mongo-csharp-driver/releases Download the MSI directly for installation or ZIP compression package. Either way, the main goal is to get two DLL files: MongoDB.Bson.dll, MongoDB.Driver.dll. This is the two class library file that you need to reference in your program.
. NET version requirements
Currently the latest version of C # driver is 1.9.2, is in. Built on the basis of NET3.5, so when using C # driver. NET version must be 3.5 and above.
The C # drive consists mainly of two namespaces: Mongodb.bson and Mongodb.driver. Most classes are non-thread-safe (thread-safe classes are: Mongoclient, Mongoserver, Mongodatabase, Mongocollection, Mongogridfs, bsonsymboltable). All static properties and methods are thread-safe.
Thread Safety
If the code is in a process where multiple threads are running concurrently, these threads may run the code concurrently. The result of each run is the same as the single-threaded run, and the values of the other variables are the same as expected, which is thread-safe.
Or, the interface provided by a class or program for a thread is an atomic operation or a switchover between multiple threads does not result in ambiguity in the execution of the interface, that is, we do not have to consider the problem of synchronization.
Thread safety issues are caused by global variables and static variables: If there are only read operations on global variables, static variables, and no write operations in each thread, in general, this global variable is thread-safe, and if more than one thread writes at the same time, it is generally necessary to consider thread synchronization, otherwise it may affect thread safety.
Create a database connection
There are several classes that you need to use to create a connection: Mongoclient, Mongoserver, Mongodatabase, Mongocollection.
Mongoclient class
The class is the root object of the MongoDB server, which represents the client (instance) of MongoDB. Database connections are made automatically in the background (by using connection pooling to improve performance). By default, all write operations are blocked until the server admits to writing.
The simplest way to create a mongoclient is to use the connection string, which has the following pattern:
Mongodb://[username:[email protected]]hostname[:p Ort][/[database][?options]]
[] indicates that the item is optional, when authentication is enabled on the MongoDB server, a user name and password are required, and when username and database are used simultaneously, the user is required to have permission to manipulate the database; When mismatched, the default database is Admin If you do not know the port number, the default port number is 27017.
When you need to connect to more than one server, use "," split between different servers, and the port number cannot be omitted, such as:
mongodb://server1:27017,server1:27018
Mongoserver class
Use the Getserver () method of mongoclient to get to the Mongoserver instance, the Getdatabase () method of the class can get to the Mongodatabase instance based on the database name. The method has the following overloads:
Mongodatabase getdatabase (mongodatabasesettings settings)
Mongodatabase getdatabase (String databaseName)
Mongodatabase getdatabase (String databaseName, mongocredentials credentials)
Mongodatabase getdatabase (String databaseName, mongocredentials credentials, Writeconcern Writeconcern)
Mongodatabase getdatabase (String databaseName, Writeconcern Writeconcern)
The following code shows how to connect to the server and get the database:
Mongoclient client = new Mongoclient (); Connect to Local
Mongoserver Server = client. Getserver ();
Mongodatabase database = server. Getdatabase ("test"); Get the test database
Mongodatabase class
The database on MongoDB can be obtained by the given database name, and the GetCollection () method of the class is used to get the mongocollection<tdefaultdocument> instance based on the collection name.
Mongocollection class
By given the collection name and using the GetCollection method of the Mongodatabase instance to get the collection object, all the additions and deletions are implemented on the basis of the collection object.
Insert Document
You can insert a document by using the Mongocollection<tdefaultdocument> insert<tdefaultdocument> () method. Tdefaultdocument can be the default bsondocument type, or it can be a user-defined type. In the case of a user-defined type, the type must have an ID field or attribute, or manually specify the name of the primary key.
public class Book
{
int Id{get;set;}
String Author {Get;set;}
String Title {Get;set;}
}
mongocollection<book> books = database. Getcollection<book> ("books"); Gets the collection named books
Book book = new Book {
Author = "Ernest Hemingway",
Title = "For Whom the Bell tolls"
};
Books. Insert (book);
The above custom type does not have an ID field or attribute defined in book, is inserted into the collection, or by default adds the _ID key to the Daily Record, and the key is the Objectid type. There is no error when inserting, but when we get the data from the database and convert the data to the book type, there is an error because the book does not have an ID field, and the _id value obtained does not know where to assign the value.
BULK Insert
Bulk insertion of documents can be done through the mongocollection<tdefaultdocument> Insertbatch () method.
Mongocollection<bsondocument> Books;
bsondocument[] Batch = {
New Bsondocument {
{"Author", "Kurt Vonnegut"},
{"title", "Cat ' s Cradle"}
},
New Bsondocument {
{"Author", "Kurt Vonnegut"},
{"title", "Slaughterhouse-five"}
}
};
Books. Insertbatch (Batch);
Bulk INSERT is more efficient than a single insert because only one connection request and processing header information is made.
The above insert document and BULK Insert demonstrate the two types of data supported by the MongoDB C # driver insert data. It's easy to customize the type, and it's in line with the habits of ADO and EF. But using custom classes involves serialization, which means that we can control which fields or properties in a class correspond to the keys in the collection. For serialized content, refer to the official documentation: http://docs.mongodb.org/ecosystem/tutorial/use-csharp-driver/
Data Lookup methods: FindOne () and Findoneas <TDefaultDocument> ()
The FindOne () method is the simplest lookup method that returns the first found document from the collection (when there are multiple documents in the collection, it is not known which document will be returned).
Mongocollection<book> Books;
Book book = books. FindOne ();
Findoneas <TDefaultDocument> () You can convert a found document to a tdefaultdocument type:
Mongocollection<book> Books;
Bsondocument document = books. Findoneas<bsondocument> ();
Findas <TDefaultDocument> ()
This method tells the server which document to return by querying the document as a parameter.
The query document is a imongoquery type and is typically constructed using its implementation class querydocument to construct the query document:
Mongocollection collection = database. GetCollection ("user");
var query = new Querydocument ("Key", "value");
Collection. Findas (typeof (Bsondocument), query);
The construction of query documents can also be constructed by MongoDB.Driver.Builders.Query, which can construct different types of documents such as equivalent queries:
Mongocollection collection = database. GetCollection ("user");
var query = Query.eq ("Key", "value");
Collection. Findas (typeof (Bsondocument), query);
save<tdocument> ()
This method combines the Insert method and the Update method. When the ID value in the saved document already exists, it is equivalent to the update () method, otherwise it is equivalent to the Insert () method.
Mongocollection<bsondocument> Books;
var query = Query.and (
Query.eq ("Author", "Kurt Vonnegut"),
Query.eq ("title", "Cats Craddle")
);
Bsondocument book = books. FindOne (query);
if (book! = null) {
book["title"] = "Cat ' s Cradle";
Books. Save (book);
}
The tdocument type of the Save method must have an ID field, otherwise, you can only use the Insert method.
Update () Method
This method is used to update a document that already exists. The update above using the Save method is equivalent to the following code:
Mongocollection<bsondocument> Books;
var query = new Querydocument {
{"Author", "Kurt Vonnegut"},
{"title", "Cats Craddle"}
};
var update = new UpdateDocument {
{"$set", New Bsondocument ("title", "Cat ' s Cradle")}
};
Bsondocument Updatedbook = books. Update (query, update);
You can also use the query and update constructors:
Mongocollection<bsondocument> Books;
var query = Query.and (
Query.eq ("Author", "Kurt Vonnegut"),
Query.eq ("title", "Cats Craddle")
);
var update = Update.set ("title", "Cat ' s Cradle");
Bsondocument Updatedbook = books. Update (query, update);
findandmodify ()
This method modifies the found document, which is typically used to update a single document. You can also combine queries to match multiple documents.
var jobs = database. GetCollection ("Jobs");
var query = Query.and (
Query.eq ("InProgress", false),
Query.eq ("name", "Biz report")
);
var sortby = sortby.descending ("priority");
var update = update.
. Set ("InProgress", True)
. Set ("Started", Datetime.utcnow);
var result = jobs. Findandmodify (
Query
SortBy,
Update
True//return new document
);
var chosenjob = result. Modifieddocument;
MapReduce ()
Map/reduce is a method of aggregating data from a collection. Each document in the collection is passed to the map function, emit, to produce an intermediate value. The median value is passed to the reduce function for aggregation operations.
var map =
"function () {" +
"For (var key in this) {" +
"Emit (Key, {count:1});" +
" }" +
"}";
var reduce =
"Function (key, emits) {" +
"total = 0;" +
"For (var i in emits) {" +
"Total + = Emits[i].count;" +
" }" +
"Return {count:total};" +
"}";
var Mr = collection. MapReduce (map, reduce);
foreach (Var document in Mr. GetResults ()) {
Console.WriteLine (document. ToJson ());
}
other properties and methods
Mongocursor<tdocument> class: The Find method does not immediately return a result, but instead returns a cursor that enumerates the results, and the query is not immediately sent to the server, but is processed by the server when it tries to receive the first result.
Enumerate cursors: Use foreach to enumerate the results that the cursor points to:
var query = Query.eq ("Author", "Ernest Hemingway");
var cursor = books. Find (query);
foreach (var book in cursor) {
}
You can also enumerate cursors through the extended Method of LINQ:
var query = Query.eq ("Author", "Ernest Hemingway");
var cursor = books. Find (query);
var firstbook = cursor. FirstOrDefault ();
var lastbook = cursor. LastOrDefault ();
The above method, the query will be sent to the server 2 times FirstOrDefault once, LastOrDefault once.
Note: Remember to release (Call the Dispose () method) when the cursor has finished traversing.
To modify a cursor before enumerating: You can modify the cursor's properties before enumerating the cursor, in two ways, one for direct modification and the other for setting properties through the fluent interface.
Skips the first 100 records of a cursor and processes only 10 records
var query = Query.eq ("status", "Pending");
var cursor = tasks. Find (query);
Cursor. Skip = 100;
Cursor. Limit = 10;
foreach (var task in cursor) {
}
The above implementation can also be used in the following way:
var query = Query.eq ("status", "Pending");
foreach (var task in tasks.) Find (query). Setskip (100). Setlimit (10)) {
Do something with task
}
Modifiable properties in Cursors: BatchSize, Fields, Flags, Limit, Options, Serializationoptions, Skip, Slaveok
Other methods: Clone, Count, Explain, Size
Writeconcern class : Whether the new, save, update, and delete operations are successful, the query operation can be judged based on the results of the query returned (whether it is empty).
Insert () returns writeconcernresult the more important attributes are: Haslasterrormessage, Lasterrormessage, Response
Update () also returns Writeconcernresult where documentsaffected represents the number of documents being updated. Updatedexisting Indicates whether there is an update, and the other is basically consistent.
The Writeconcernresult returned by the Save () and remove () methods is consistent with update ().
Set time-out for lookup: collection. FindAll (). Setmaxtime (Timespan.fromseconds (1)); When more than 1 seconds, the query is aborted.
Bulk Operations (batch add, update, delete)
There are two ways to do bulk operations, one to execute on the order of operations, and to return the information on the first error, one to not execute the operation, and to return all the information that went wrong.
Batch operations performed sequentially:
Bulkwriteoperation Bulk = collection. Initializeorderedbulkoperation ();
Bulk. Insert (New Bsondocument ("_id", 1));
Bulk. Insert (New Bsondocument ("_id", 2));
Bulk. Insert (New Bsondocument ("_id", 3));
Bulk. Insert (New Bsondocument ("_id", 4));
Bulk. Find (Query.eq ("_id", 1)). Update (Update.set ("name", "Wangdh1"));
Bulk. Find (Query.eq ("_id", 2)). Remove ();
Bulk. Find (Query.eq ("_id", 3)). Replaceone (New Bsondocument ("_id", 3). ADD ("name", "Wangdh3"));
Bulkwriteresult Bulkresult = bulk. Execute ();
Bulk operations performed in parallel:
Bulkwriteoperation Bulk = collection. Initializeunorderedbulkoperation ();
Bulk. Find (Query.eq ("_id", 1)). Removeone ();
Bulk. Find (Query.eq ("_id", 2)). Removeone ();
Bulkwriteresult Bulkresult = bulk. Execute ();
Return value for bulk operation: Bulkwriteresult
Important attributes are: Deletedcount, Insertedcount, Modifiedcount, Matchedcount, processedrequests, respectively, the number of deletions, inserts, updates, checks found, and requests generated during processing.
base class: Bson namespace
The Bson class library is the basis for C # drivers, and the details of processing include: I/O, serialization, and Bson the memory object model of the document. The important Bson object models are: Bsontype, Bsonvalue, Bsonelement, Bsondocument, Bsonarray.
Bsontype: Represents the type of Bson, which is an enumeration type.
An abstract representation of the value of Bsonvalue:bson
Bsonelement: is a name/value representation of the key-value pair type
Bsondocument: is a bsonelement (key-value pair) collection
To create an inline bsondocument:
Bsondocument nested = new Bsondocument {
{"Name", "John Doe"},
{"Address", new Bsondocument {
{"Street", "123 Main St."},
{"City", "Centerville"},
{"state", "PA"},
{"Zip", 12345}
}}
};
Processing bsondocument: Since Bsondocument is a collection of key-value pairs, the corresponding value can be obtained by the key name, and then the obtained value is converted to the appropriate type by the Asxxx method.
Bsondocument Book;
String author = book["Author"]. asstring;
DateTime publicationdate = book["Publicationdate"]. Asdatetime;
int pages = book["Pages",-1]. AsInt32;
Bsonarray:bson Array
MongoDB Learning Compare -07 C # drive Operation MongoDB