MongoDB advanced Query "two"

Source: Internet
Author: User
Tags mongoclient mongodb query

Previous article, wrote MongoDB General operation, continue to write, this chapter mainly talk about advanced query, text, aggregation, Big Data query.

MongoDB has a lot of query syntax and is a richer one in the NoSQL ranks. Of course, there are many queries that cannot be compared with relational queries. For instance, MongoDB is not good at querying tables, although a $lookup supports the association between two sets, but is less than the relationship.

MongoDB query kind is very rich, here do not explain, pick some commonly used to write, make a note.

a Aggregate Queries

MongoDB aggregates queries against data statistics, filtering references aggregate (). Features are quite powerful.

Several common operators

$project: Modify the structure of the document (rename, add, or delete fields), or you can use it to create calculations and nested documents.

$unwind: Splits one of the array type fields in the document into multiple bars, each containing a value in the array.

$match: Filter the data to only output documents that match the criteria.

$limit: Limits the number of documents returned by the MongoDB aggregation pipeline.

$skip: Skips a specified number of documents in the aggregation pipeline.

$group: Groups The documents in the collection to be used for statistical results.

$sort: Document sort output.

$sum Calculate sum

These are the most commonly used operators, which must be mastered in MongoDB. The following one, one with the net core example, will still use the first data structure of this series, the students who do not know can go to see the first article.

Let's try to add some simulation data to facilitate the program testing.

classprogram{Static voidMain (string[] args) {mongoclient Client=NewMongoclient ("mongodb://192.168.99.5"); Imongodatabase Dbbase= client. Getdatabase ("School"); Imongocollection<Class> collection = Dbbase.getcollection<class> ("Class"); //generate random numbers usingRandom random =NewRandom (); varNAMEITEMS1 ="Zhao, Qian, Sun, Li, Zhou, Wu, Zheng, Wang, Feng, Chen, Chu, Wei, Jiang, Shen, Han, Yang, Zhu, Qin, especially, Xu, ho". Split (",").        ToList (); varNAMEITEMS2 ="Hope Li, red, sweet, ladies, Binbin, silverred, Dawn, Ting, Guang Rong, Becky, Xiao Yan, Xin Ru, Fu Ren, Jia, Wen Ting". Split (",").        ToList ();  for(vari =1; I <7; i++) {collection. Insertone (NewClass {ClassName= $"{i} grade", Studentitems= ((func<list<student>>) (() =                {                    varStudentitems =NewList<student>(); varStudentcount = random. Next (5, the);  for(vart =0; T < Studentcount; t++) {Studentitems.add (NewStudent { age= Random. Next (6, A), Name= Nameitems1[random. Next (0, Nameitems1.count)] + nameitems2[random. Next (0, Nameitems2.count)], Sex= Random. Next (1,3) ==1?"male":"female"                        }); }                    returnStudentitems;        }))()            }); }    }} Public classclass{ PublicBsonobjectid Id {Set;Get; }  Public stringClassName {Set;Get; }  PublicList<student> Studentitems {Set;Get; }} Public classstudent{ Public stringName {Set;Get; }  Public intAge {Set;Get; }  Public stringSex {Set;Get; }}

Collection. Aggregate<>// is a generic method, the return type can be bsondocument or entity, and is automatically serialized.  /// for example collection. Aggregate<bsondocument>() collection. Aggregate< entity class >()// It is worth mentioning that Aggregate () accepts the parameter pipelinedefinition, Instead, the implicit type conversion operator is used in the Pipelinedefinition class. So directly input parameters can be

$project operator

var items = collection. Aggregate<bsondocument> (new[] {    new"$project" New Bsondocument ("studentitems"1)}}). ToList ();

Result: You will find that Studentitems is extracted separately.

$unwind operator

var items = collection. Aggregate<bsondocument> (new[] {    new bsondocument ("$unwind ","$StudentItems")}). ToList ();

Result: You will find that each of the studentitems is drawn out to form a new document with the original document

In general, $project and $unwind are used in combination. such as extracting studentitems each item to form a document. For example

var items = collection. Aggregate<bsondocument> (new[] {    new"$project" New Bsondocument ("studentitems"1)}},    new Bsondocument ("$unwind","$StudentItems") }). ToList ();

Results:

$match operator

var items = collection. Aggregate<bsondocument> (new[] {    new"$match"  New bsondocument ("ClassName""1 grade ")} }}). ToList ();

Results:

$limit operator

$skip operator

var items = collection. Aggregate<bsondocument> (new[] {    new bsondocument ("$skip ",2),    new bsondocument ("$limit", 3 )}). ToList ();

Result: After skipping the top two, select the first three bars. For example: Apps that are grouped into pagination

$group operator

$sum operator

varItems = collection. Aggregate<bsondocument> (New[] {    Newbsondocument {{"$group",Newbsondocument {{"_id",NewBsondocument ("ClassName","$ClassName")},            { "Count",NewBsondocument ("$sum",1) }}        }     }}). ToList ();

Results: Grouped by grade and counting the total number of rows per group

$sort operator

var items = collection. Aggregate<bsondocument> (new[] {    new  bsondocument {        " $sort " New Bsondocument ("ClassName",-1)}}). ToList ();

Note: The order of the operators is important, and the order of precedence will result in different results.

MongoDB aggregation query, note here.

MongoDB advanced Query "two"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.