This is mainly about the bottom of my package, does not involve MongoDB installation, start-up, visual query and other things, will be accompanied by a number of reference addresses for everyone to study together.
There are currently two main types of drivers available for MongoDB:
1. Official website driver Download Address: http://github.com/mongodb/mongo-csharp-driver/downloads
2. Third-party Samus driver download address: Https://github.com/samus/mongodb-csharp
Two drivers have been used in their own use, personal sense of the official drive to provide a more convenient way to use it , and newer than Samus, so they are using the official drive.
Official website-driven simple use
mainly uses the following two DLLs
mongodb.dll Driven Main program
mongodb.gridfs.dll is used to store large files.
Basic additions and deletions to the code are as follows:
Database connection string const string strconn = "mongodb://127.0.0.1:27017";
Database name const string dbname = "Cnblogs";
Define Database mongodatabase db; <summary>/// Open the database link/// </summary> public void getconnection () {//
Define Mongo service mongo mongo = new mongo (strconn); Open the connection mongo.
Connect (); Obtains the database cnblogs, if does not exist then automatically creates the db = mongo.
Getdatabase (dbname) as MongoDatabase; /// <summary>/// Add Data/// </summary> Public void insert () {Var col = db.
Getcollection<users> (); or //var col = db.
GetCollection ("Users");
Users users = new users (); Users.
name = "Xumingxiang"; Users.
sex = "Man"; Col.
Insert (users); /// <summary>/// Update Data/// </summary> public void update () {Var col = db.
Getcollection<users> (); //detect the first record of the name value of Xumingxiang users users = col.
FindOne (x => x.name == "Xumingxiang"); or //users users = col.
FindOne (new document { { "Name", "Xumingxiang" &NBSP;}&NBSP;}); users.
sex = "Women"; Col.
Update (users, x => x.sex == "man"); /// <summary>/// Delete Data/// </summary> public void delete () {Var col = db.
Getcollection<users> (); Col.
Remove (x => x.sex == "man"); Or////find the first record of the name value Xumingxiang //users users = col.
FindOne (x => x.sex == "man"); Col.
Remove (users); /// <summary>/// Query Data/// </summary> public void query () {Var col = db.
Getcollection<users> ();
var query = new document { { "Name", "Xumingxiang" } }; InquireSpecify all data var result1 = col for the query criteria.
Find (query); query specifies the first data var result2 = col of the query criteria.
FindOne (query); Query the data var result3 = col in all collections.
FindAll (); }
Encapsulation Extension Use
1. Database configuration file
Consider the possibility of using a different database in a project, such as: ordinary data and file data, etc. are stored in different databases, and may also query across servers, so here first create a profile help class, mainly can be a number of database configuration to meet the requirements across the server, across the data.
The configuration format is as follows:
<?xml version= "1.0" encoding= "Utf-8"?>
<ServiceConfig>
<mongodbs>
<item dbname= " MyDb "Hostname=" mongodb://127.0.0.1:27017 "></Item> <item dbname=" myDb1 "hostname=" mongodb://
127.0.0.1:27017 "></Item>
<item dbname=" myDb2 "hostname=" mongodb://127.0.0.1:27017 "></item" >
</mongodbs>
</ServiceConfig>
XML Serialization Object class
public class ServiceConfig
{
[XmlArray, XmlArrayItem (' Item ')] public
list<mongodbconfig> MongoDB s {get; set;}
}
[XmlRoot]
public class Mongodbconfig
{
[XmlAttribute (' dbname ')] public
string dbname {get; set;}
[XmlAttribute ("HostName")]
public string HostName {get; set;}
}
Read configuration file Management class
Public class managerconfig { public static string ConfigPath;
//Load configuration file static managerconfig () {
ConfigPath = "./config.xml"; &NBSP;&NBSP;&NBSP;&NBSP} //xml object after serialization private static
serviceconfig _settings;
public static serviceconfig servicesettings { get { return _settings ??
(_settings = load ()); } } // Load XML serialization to ServiceConfig Object static serviceconfig load () { if (file.exists (configpath)) { using (Filestream fs = new filestream (configpath, filemode.open)) { xmlserializer xs = new xmlserializer (
typeof (ServiceConfig));
//serialized as an object _settings = (ServiceConfig) xs.
Deserialize (FS); } } eLSE {
throw new exception ("Database configuration file does not exist, please check"); //_settings = new
ServiceConfig (); } return _
Settings &NBSP;&NBSP;&NBSP;&NBSP}}
2. Entity General interface
There is no mongodb in itself, with a objectid, in order to unify each entity object has this ID, here to establish a common interface and a low-level entity base class to standardize processing
Entity interface
Public interface imongoentity
{
string Id {get;}
}
Underlying entity base class
public class basemodel:imongoentity
{
[Bsonignore] public
string Id
{
get {
if (_id = = objectid.empty)
_id = Objectid.generatenewid (DateTime.Now);
return _id. ToString ();
}
[Bsonid]
private ObjectId _id;
}
Examples of entity classes (inherited from the Basemodel class)
public class Userentity:basemodel
{public
string UserName {get; set;}
public int Num {get; set;}
The time stored in MongoDB is the standard time UTC +0:00 (8 hours apart)
[bsondatetimeoptions (Kind = datetimekind.local)] public
DateTime posttime {get; set;}
}
3.Mongodb Common help base class (main Class)
public class mongodbbase<t> where t : class,imongoentity {
protected MongoServer server = null;
protected MongoDatabase db = null;
protected MongoCollection<T> collection; protected void init (string dbname) { var item = managerconfig.servicesettings.mongodbs.where (P => p.dbname == dbname).
FirstOrDefault (); if (item == null) { throw new
exception ("There is no configuration object that has a database of: " + DbName + " , please check"); } &nbsP; else {
server = mongodb.driver.mongoserver.create (Item.hostName); db = server.
Getdatabase (Item.dbname); collection = db. Getcollection<t> (typeof (T).
Name.replace ("Entity", ")"); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}  } #region Query /// <summary> /// get object by ID /// </summary> /// <param name= "id" ></param > /// <returns></returns> public t getmodelbyid (string id) {&NBSp; return collection.
Findonebyid (ID); } /// <summary> /// Get a record (custom condition) /// </summary> /// <returns> </returns> public t firstordefault (Expression<func<t, bool >> expression) { Mongodb.driver.imongoquery query = query<t>.
Where (expression); return collection.
FindOne (query); } /// <summary> /// Get a record /// </summary> /// <returns></ Returns> public t firstordefault () {
return collection. FindAll ().
FirstOrDefault ();
&NBSP;&NBSP;&NBSP;&NBSP} /// <summary> /// get all /// </summary> /// <returns></returns > public list<t> findall () { return collection. FindAll ().
ToList (); &NBSP;&NBSP;&NBSP;&NBSP} /// <summary> /// get all (custom condition) /// </summary> /// <returns></ Returns> public list<t> findall (Expression<func<t, bool >> expression) { Mongodb.driver.imongoquery query = query< T>.
Where (expression); return collection. Find (query).
ToList (); } /// <summary> /// Acquire quantity /// </summary> /// <param name= according to the condition "Expression" ></param> /// <returns></returns> public long getcount (expression<func<t, bool>> expression = null) { if (expression = = null) { return collection.
Count (); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP} else { &Nbsp; return collection. Count (QUERY<T>.
Where (expression)); } ///
<summary> /// based on ID to determine whether there is /// </summary> /// <param name= "id" ></param> /// <returns></returns> public bool exists (string id) { return collection.
Findonebyid (ID) != null;
&NBSP;&NBSP;&NBSP;&NBSP} /// <summary> /// Paging /// </summary> /// <param name= " PageIndex "> Total page number </param> /// <param name=" PageSize "> Page capacityQuantity </param> /// <param name= "rowcounts" > Total record number </param> /// <param name= "expression" > Conditions </param> /// <param name= "ISASC" > is positive sequence </param> /// <param name= " orderfiled > Sorted fields </param> /// <returns></returns> public list<t> page (int pageindex, int pagesize, out long rowcounts, expression<func<t, bool>> expression = null,
bool isasc = true, params string[] orderfiled) {
MongoCursor<T> mongoCursor; //Condition Selection if (expression != null) &NBSP;&NBsp; { rowcounts = collection. Find (QUERY<T>. Where (expression)).
Count (); mongocursor = collection. Find (QUERY<T>.
Where (expression)); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP} else { rowcounts = collection. FindAll ().
Count (); mongocursor = collection.
FindAll (); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP} //Sort if (orderfiled != null && orderfiled.length > 0) { // Handling primary key fields for (int i = 0; i < orderfiled.length; i++) { if (orderfiled[i). Equals ("id", stringcomparison.currentcultureignorecase)) {
OrderFiled[i] = "_id"; } } & Nbsp; if (ISASC) { mongocursor
= mongocursor.setsortorder (sortby.ascending (orderfiled)); } else {
Mongocursor = mongocursor.setsortorder (sortby.descending (orderfiled)); } &NBSP;&NBSP} return mongocursor.setskip (PageIndex - 1) * pagesize). Setlimit (PageSize).
ToList (); } #region Low efficiency, no ///// <summary> ///// pagination ///// </summary> ///// < Returns></returns> //public list<t> page (Int PageIndex, int PageSize, out long RowCounts, Expression<Func<T, bool> > expression = null) //{ //
List<T> ret = new List<T> ();
// IQueryable<T> queryable; // //Condition Selection // if (expression != null) // { // queryable = cOllection. Find (QUERY<T>. Where (expression)).
AsQueryable ();
// } // else // { // queryable = collection. FindAll ().
AsQueryable (); // } // rowcounts = queryable.
Count (); // ret = queryable. Skip ((pageindex - 1) * pagesize). Take (PageSize).
ToList ();
// return ret; //} ///// <summary> ///// Pagination ///// </summary> ///// <typeparam name= "TKey" ></typeparam> <param name= "PageIndex" ></param> ///// <param Name= "PageSize" ></param> ///// <param name= "rowcounts" ></ param> ///// <param name= "expression" ></param> ///// <param name= "by" ></param> ///// <
Param name= "Isorder" ></param> ///// <returns></returns> //public List<T> Page<TKey> (int pageindex, int pagesize, out long rowcounts, expression<func<t, bool>> Expression = null, expression<func<t, tkey>> orderby = null, bool isorder = true) //{ // list<t> ret = new list<t> ();
// IQueryable<T> queryable; // //Condition Selection // if (expression != null) // { // queryable = collection. Find (QUERY<T>. Where (expression)).
AsQueryable ();
// } // else // { // queryable = collection. FindAll ().
AsQueryable ();
&NBSP;&NBSP;&NBSP;&NBSP;//&NBSP;&NBSP;&NBSP;&NBSP} // //Sort // if (orderby != null) // { // if (isorder) // { // queryable = Queryable.
by (by); // } // else // { // queryable = queryable.
OrderByDescending (by); // } // &NBSP;&NBSP;&NBSP} // rowcounts = queryable.
Count (); // &nBsp;ret = queryable. Skip ((pageindex - 1) * pagesize). Take (PageSize).
ToList ();
// return ret; //} #endregion #endregion #region Delete /// <summary> /// Delete with conditions /// </summary> /// <param Name= "expression" ></param> /// <returns></returns>
public void delete (expression<func<t, bool>> expression) { mongodb.driver.imongoquery query = query<t>.
Where (expression); var result = collection.
Remove (query); &nBSP;} /// <summary> /// Delete by model
/// </summary> /// <param name= "Model" ></param> public void delete (T model) { mongodb.driver.imongoquery query = query<t>. Where (P => p.id == model.
ID); collection.
Remove (query); } /// <summary> /// Delete by id /// </summary> /// <param name= " Id "></param> public void delete (string id) { mongodb.driver.imongoquery query = query <T>.
Where (P => p.id == id); collection.
Remove (query);
&NBSP;&NBSP;&NBSP;&NBSP} /// <summary> /// Delete all /// </summary> /// <returns></returns > public void deleteall () { var result = collection.
RemoveAll (); &NBSP;&NBSP;&NBSP;&NBSP} #endregion #region Add /// <summary> /// Single model add /// </summary> /// <param name= "model" ></param> /// <returns></returns> public void insert (T model) { var result = collection.
Insert<t> (model);
&NBSP;&NBSP;&NBSP;&NBSP} /// <summary> /// Bulk add /// </summary> /// <param name= "Model" ></param> /// <returns></returns> Public void insertbatch (List<t> model) { collection.
Insertbatch<t> (model); &NBSP;&NBSP;&NBSP;&NBSP} #endregion #region Modify /// <summary> /// Modify /// </ summary> /// <param name= "model" ></param> /// <returns></rEturns> public void update (T model) { var result = collection.
Save<t> (model);
&NBSP;&NBSP;&NBSP;&NBSP} /// <summary> /// Bulk modification /// </summary> /// <param name= "Model" ></param> public void updateall (List<t> model) { model. ForEach (e => collection.
Save<t> (e)); &NBSP;&NBSP;&NBSP;&NBSP} #endregion}
4. Business Class
When you create a new table (called a collection in MongoDB), you need to manipulate it, including some business processes. Inherit the Mongodbbase class first, and then initialize the object using the Init method, such as the following Userservcices class
public class userservices:mongodbbase<userentity>
{public
userservices ()
{
this.i NIT ("MyDb");
}
}
5. Use
[TestClass] Public class unittest1 { random rd = new random
();
userservices ubll = new userservices (); #region Add [testmethod] public void Add () { UserEntity
Model = new userentity (); model. username = "Name" + rd.
Next (100, 10000); model. Num = rd.
Next (100, 10000); model.
posttime = datetime.now; ubll.
Insert (model); &NBSP;&NBSP;&NBSP;&NBSP} [testmethod] public void Add complex Model () { complexentity model = new complexentity (); complexservices cbll = new complexservices
(); model.
name = "Complex"; model.
Schools = new list<school> (); model. Schools.add (New school () { master = new grade () { Name = "Master" &NBSP;&NBSP;&NBSP}, Name = " School ",
Students = new List<
Student> () }); model. Schools[0].
Students.add (New student () { Age = 22, Name = "John" &NBSP;}); cbll.
Insert (model); &NBSP;&NBSP;&NBSP;&NBSP} [testmethod] public void Bulk Add () { List<UserEntity>
Data = new list<userentity> (); for (int i = 0; i < 1000000; i++) {
userentity model = new userentity (); &nbsP; model. username = "Name" + rd.
Next (100, 10000); model. Num = rd.
Next (100, 10000); model.
posttime = datetime.now;
data.add (model); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP} ubll.
Insertbatch (Data); &NBSP;&NBSP;&NBSP;&NBSP} #endregion #region Modify
[testmethod] public void Get a single object _ Modify () { var model = ubll.
FirstOrDefault (p => p.id != ""); model. username = "
New1 "; ubll.
Update (model); &NBSP;&NBSP;&NBSP;&NBSP} [testmethod] public void Batch modification () {&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;VAR&NBSP;MODEL&NBSP;=&NBSP;UBLL .
FindAll (); for (int i = 0; i < Model. count; i++) { model[i].
username = "Text"; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP} ubll.
UPDATEALL (model); &NBSP;&NBSP;&NBSP;&NBSP} #endregion #region Query [testmethod] public void Get all objects () { var Model = ubll.
FindAll (); var count = model.
Count; &NBSP;&NBSP;&NBSP;&NBSP} [testmethod] public void Get a single object () { var model = Ubll.
FirstOrDefault (); var count = model.
Posttime; &NBSP;&NBSP;&NBSP;&NBSP} [testmethod] public void Get object based on ID () { var model = Ubll.
Getmodelbyid ("eeef22d6-7ac6-40cd-9312-59ab15fd904a"); &NBSP;&NBSP;&NBSP;&NBSP} [testmethod] public void Get all pair condition like _ with condition () { var model = ubll. FindAll (P => p.usernamE.contains ("Name")); var count = model.
Count; &NBSP;&NBSP;&NBSP;&NBSP} [testmethod] public void paging ( ) { long Rows; List<UserEntity> pageDate = new List<UserEntity>
(); pagedate = ubll.
Page (300, 20, out rows, p => p.num > 1500); pagedate = ubll.
Page (1, 20, out rows, null, true, "Id"); pagedate = ubll.
Page (1, 20, out rows, null, true, "Num"); pagedate = ubll. Page (1, 20, out 
rows, p => p.num > 1500, false, "Id"); &NBSP;&NBSP;&NBSP;&NBSP} [testmethod] public void Get Quantity () { //without conditions var count = ubll.
GetCount (); //with conditions var Count1 = ubll.
GetCount (p => p.num > 5000); &NBSP;&NBSP;&NBSP;&NBSP} #endregion #region Delete
[testmethod] public void Delete _ custom condition () { ubll.
Delete (p => p.num >= 2000); &NBSP;&NBSP;&NBSP;&NBSP} [testmethod] public void Delete _ Delete model () { var model = Ubll.
FirstOrDefault (); if (model != null) {&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;UBLL.
Delete (model);
} } [testmethod] public void Delete _ Delete by ID () { ubll.
Delete ("Ec45ea8b-a551-46eb-ad58-1b4f5f2aab25"); &NBSP;&NBSP;&NBSP;&NBSP} [testmethod] public void Delete _ Remove all () {&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;UBLL.
DeleteAll (); &NBSP;&NBSP;&NBSP;&NBSP} #endregion #region Other [testmeThod] public void Create two objects at the same time _ in the same database () {
logservices logbll = new logservices ();
userentity model = new userentity (); model. username = "Name" + rd.
Next (100, 10000); model. Num = rd.
Next (100, 10000); model.
posttime = datetime.now; ubll.
Insert (model);
logentity log = new logentity (); log. username1 = "Name" + rd.
Next (100, 10000); log. Num1 = rd.
Next (100, 10000); &nbSp; log.
posttime1 = datetime.now;
logbll.insert (log); model. username = "Name" + rd.
Next (100, 10000); model. Num = rd.
Next (100, 10000); model.
posttime = datetime.now; ubll.
Insert (model); &NBSP;&NBSP;&NBSP;&NBSP} [testmethod] public void Create two objects at the same time _ different database () { Log1Services
Logbll = new log1services ();
userentity model = new userentity (); model. username = "Name" + rd. Next (100, 10000); model. Num = rd.
Next (100, 10000); model.
posttime = datetime.now; ubll.
Insert (model);
logentity log = new logentity (); log. username1 = "Name" + rd.
Next (100, 10000); log. Num1 = rd.
Next (100, 10000); log.
posttime1 = datetime.now;
logbll.insert (log); model. username = "Name" + rd.
Next (100, 10000); model. Num = rd.
Next (100, 10000); &nbSp;model.
posttime = datetime.now; ubll.
Insert (model); &NBSP;&NBSP;&NBSP;&NBSP} [testmethod] public void When the specified name does not exist () { errorservices error
= new errorservices (); &NBSP;&NBSP;&NBSP;&NBSP} #endregion}
The above is their own encapsulation of the overall logic and code, but there are some do not understand and lack of place, here put forward, I hope the great God to help me answer:
1. Return value problem
In Tim, delete, change the use, according to the website provided by the driver, there is a Writeconcernresult object returned, but in the test found that this returned object is always null
2. Increase the ID problem
There is no mongodb in itself, with a objectid, if I need an ID, do I build one, and then I control +1 on the increase? However, this performance is relatively low, but also to consider the case of multithreading concurrency lock problem. So I don't know how this is going to happen.
3. Paging Efficiency issues
First page I was to turn the results into queryable, then in the operation, this code has this paragraph, temporarily commented out, the back of the blog to see a predecessor of the MongoDB analysis, changed the next page of the way, the test is very fast, but in the condition of the total number of records to get the time, found that the test 300W data, to get the total number of 600ms required time, I do not know whether the method is wrong or other better?
MongoDB Method and performance of paging query
This article focuses on MongoDB paging queries, why? Paging is a common number one killer, bad, the customer scold, the manager scolded.
Traditional SQL paging
Traditional SQL paging, all the scenarios are almost row_number, for the need for a variety of sorting, complex query scenarios, Row_number is the killer. In addition, for the current web is very popular Poll/push load paging, the time stamp is generally used to achieve pagination. These two kinds of pagination can be said that the former is universal, even LINQ generated paging is Row_number, it is conceivable that it more general. The latter is the best of both performance and complexity, as long as a simple timestamp can be.
MongoDB page
Enter into the MONGO of ideas, pagination is not difficult, what is rare? In fact, there is nothing, see understand also that way, and the idea of SQL paging is consistent.
First describes the use cases for this article, and I have imported the following Entity data in the database, where cus_id, amount I was born into an orderly number, the number of records poured is 200w:
public class test { /// <summary> /// primary Key ObjectId is MONGODB with its own primary key type /// </summary> public objectid id { get; set; } /// <summary> /// Customer number /// </summary> [bsonelement ( "cust_id")] public string CustomerId { get; set; } /// <summary> /// Total /// </summary > [bsonelement ("Amount")] public int amount { get; set; } / <summary> /// Status /// </summary> [bsonelement ( "status")] public string Status { get; &NBSP;SET;&NBSP}}
First take a look at the paging required parameters and results, the general paging required parameters are:
PageIndex Current Page
PageSize per page record number
Queryparam[] Other query fields
So according to Row_number's paging idea, that is, to take the first (pageindex*pagesize) to the (Pageindex*pagesize + pageSize), we use LINQ to express:
Query. Where (xxx...xxx). Skip (pageindex*pagesize). Take (PageSize)
Look up the data, there is a skip function, and there are limit functions see Resources 1, 2, so easy to implement such a paging query:
Db.test.find ({xxx...xxx}). Sort ({"Amount": 1}). Skip (a) limit (10)//Here ignore the query statement
Quite efficient, almost a few milliseconds out of the result, is really nosql efficiency first-class. But slow, the data I use here is only 10, and there is not much data. I add the data to 100000 and the efficiency is about 20ms. If this is the end of the study, it is really too much to live up to the spirit of the program ape to delve into. SQL Paging scheme, but there are a lot of, the efficiency is also different, that MONGO is this kind of, the answer is obviously not such. Is there a problem with performance in addition to efficiency? Redis in the article, have eaten such a loss, disorderly use the keys.
After reviewing some of the information, I found that all the information is as follows:
Do not easily use skip to do the query, otherwise the large amount of data will lead to a sharp decline in performance, this is because Skip is a one of the number over, more naturally slow.
So, skip is to avoid the use of, so how to avoid it? First of all, review the SQL page after a timestamp paging scheme, this use of the ordered nature of the field, using the query to fetch data, you can directly avoid a large number of digital. In other words, if you can attach such conditions to the query efficiency will improve, in fact, this is it? Let's verify:
Here we assume that the query 100,001th data, the amount value of this data is: 2399927, we write two statements, respectively, as follows:
Db.test.sort ({"Amount": 1}). Skip (100000). Limit (a)//183ms
Db.test.find ({amount:{$gt: 2399927}}). Sort ({"Amount": 1}). Limit (a)//53ms
The results have been attached to the annotations, and it is clear that the latter performance is One-third of the former, and the gap is very large. Also confirms the theory that skip efficiency is poor.
C # Implementation
We've already talked about the statement and efficiency of MongoDB paging, so let's implement the C # driver version.
The official Bson drive is used in this article, as detailed in reference 4. Mongo drive comes with another way one is similar to Ado.net's native query, one of which is LINQ, where both of us are implemented
Scenario One: Conditional Query native query implementation
var query = Query<test>. GT (item => item. Amount, 2399927);
var result = collection. Find (query). Setlimit (100)
. SetSortOrder (sortby.ascending ("Amount")). ToList ();
Console.WriteLine (Result. A (). Tojson ());//bson with Tojson
Program two: Skip native query implementation
var result = collection. FindAll (). Setskip (100000). Setlimit (100)
. SetSortOrder (sortby.ascending ("Amount"));
Console.WriteLine (Result. ToList (). A (). Tojson ());
Scenario Three: Linq condition query
var result = collection. Asqueryable<test> (). By (item => item). Amount)
. Where (item => item. Amount > 2399927). Take (100);
Console.WriteLine (Result. A (). Tojson ());
Scenario Four: Linq Skip version
var result = collection. Asqueryable<test> (). By (item => item). Amount). Skip (100000). Take (100);
Console.WriteLine (Result. A (). Tojson ());
Performance Comparison Reference
The test code here later I upload, the specific implementation is to use the old Zhao (my idol ah ~) Codetimer to calculate performance. In addition, I run the code is used Testdriven Plug-ins to run.
Programme I:
Pagination Gt-limit
{"_id": ObjectId ("5472e383fc46de17c45d4682"), "cust_id": "A12399997", "Amount": 2399928, "STA Tus ":" B "} time
elapsed:1,322ms
CPU cycles:4,442,427,252
gen 0:0
Gen 1:0
G En 2:0
Programme II:
Pagination Skip-limit
{"_id": ObjectId ("5472e383fc46de17c45d4682"), "cust_id": "A12399997", "Amount": 2399928, "s Tatus ":" B "} time
elapsed:95ms
CPU cycles:18,280,728
gen 0:0
Gen 1:0
Gen 2 : 0
Programme III:
Paginatilinq on Linq where
{"_id": ObjectId ("5472e383fc46de17c45d4682"), "cust_id": "A12399997", "Amount": 2399928 , "status": "B"} time
elapsed:76ms
CPU cycles:268,734,988
gen 0:0
Gen 1:0
Gen 2:0
Programme IV:
Pagination Linq Skip
{"_id": ObjectId ("5472e383fc46de17c45d4682"), "cust_id": "A12399997", "Amount": 2399928, "STA Tus ":" B "} time
elapsed:97ms
CPU cycles:30,834,648
Gen 0:0 Gen
1:0
Gen 2: 0
The result is not tumbling glasses, this and theory is too big, the first time why and behind the gap so big? At first I thought it was the driver of C # MONGO, trying to change the drive. These days I was watching "MongoDB in action" when I found the article mentioned:
MongoDB will load the index and metadata of the document into memory based on the query, and suggest that the size of the document metadata should always remain less than the machine memory, otherwise performance will decrease.
After noticing the above theory, I replaced my test plan, the first execution was excluded, and then compared, and found that the result was actually normal.
Revised results of programme I:
Pagination Gt-limit
{"_id": ObjectId ("5472e383fc46de17c45d4682"), "cust_id": "A12399997", "Amount
": 2399928 , "status": "B"} time
elapsed:18ms
CPU cycles:54,753,796
gen 0:0
Gen 1:0
gen 2:0
Summarize
This article, based on the skip pagination and ordered field query paging two kinds of scenarios for comparison. The latter simply uses the results of the query to improve performance by not counting sequentially. Skip although less efficient but general some, ordered field query, need to design the page in the time to do some processing of this field, at least the number of points can get to this field. Here I attach a way, is the combination of the two, we can take each display of the page data on the last one, combined with skip to deal with pagination, so that is relatively better. There is no concrete implementation here. Other ways of performance comparison and implementation, welcome Daniel to share, thank you very much. In addition, if there are flaws and deficiencies in this article, please comment.