Mongodb進階查詢【二】

來源:互聯網
上載者:User

標籤:mongod   篩選   list   mongodb   pos   getc   進階   gpo   ==   

上一篇文章,寫了 mongodb常規操作,繼續寫入,本章主要講進階查詢,文本,聚集,大資料查詢。

Mongodb的查詢文法是很多的,是NOSQL隊伍中比較豐富的一個。當然有很多查詢跟關係型查詢無法相比。例如聯表查詢,Mongodb並不擅長聯表查詢,雖然出一個$lookup支援兩個集合之間關聯,不過跟關係相比之就遜色多了。

 Mongodb的查詢種類很豐富,這裡就不一一講解,挑一些常用的寫出來,作一個筆記。

一  彙總查詢

mongodb對資料統計,篩選引用aggregate()進行彙總查詢。功能相當強大。

常用幾個操作符

$project:修改文檔的結構(重新命名、增加或刪除域),也可以用於建立計算結果以及嵌套文檔。

$unwind:將文檔中的某一個數群組類型欄位拆分成多條,每條包含數組中的一個值。

$match:過濾資料,只輸出合格文檔。

$limit:限制MongoDB彙總管道返回的文檔數。

$skip:在彙總管道中跳過指定數量的文檔。

$group:將集合中的文檔分組,可用於統計結果。

$sort:文檔排序輸出。

$sum 計算總和

 

以上這幾個操作符,是最常用的,mongodb中必須要掌握的操作符。下面一個,一個用net core樣本講解,將依然使用這個 系列第一篇資料結構,有不瞭解的同學可以去看一看第一篇。

我們先嘗試添加一些類比資料,以方便程式測試。

class Program{    static void Main(string[] args)    {        MongoClient client = new MongoClient("mongodb://192.168.99.5");        IMongoDatabase dbBase = client.GetDatabase("School");        IMongoCollection<Class> collection = dbBase.GetCollection<Class>("Class");        //產生隨機數使用        Random random = new Random();        var nameItems1 = "趙、錢、孫、李、周、吳、鄭、王、馮、陳、楮、衛、蔣、沈、韓、楊、朱、秦、尤、許、何".Split("、").ToList();        var nameItems2 = "盼麗、豔紅、甜甜、璨、彬彬、銀紅、晨曦、婷、廣榮、蓓、小豔、欣如、輔仁、嘉、雯婷".Split("、").ToList();        for (var i = 1; i < 7; i++)        {            collection.InsertOne(new Class            {                ClassName = $"{i}年級",                StudentItems = ((Func<List<Student>>)(() =>                {                    var studentItems = new List<Student>();                    var studentCount = random.Next(5, 15);                    for (var t = 0; t < studentCount; t++)                    {                        studentItems.Add(new Student                        {                            Age = random.Next(6, 12),                            Name = nameItems1[random.Next(0, nameItems1.Count)] + nameItems2[random.Next(0, nameItems2.Count)],                            Sex = random.Next(1, 3) == 1 ? "男" : "女"                        });                    }                    return studentItems;                }))()            });        }    }}public class Class{    public BsonObjectId Id { set; get; }    public string ClassName { set; get; }    public List<Student> StudentItems { set; get; }}public class Student{    public string Name { set; get; }    public int Age { set; get; }    public string Sex { set; get; }}

collection.Aggregate<>//是一個泛型方法,傳回型別可以是BsonDocument或實體,自動序列化。//例如collection.Aggregate<BsonDocument>()collection.Aggregate<實體類>()//值得一提的是Aggregate()接受的參數是PipelineDefinition,而PipelineDefinition類中使用implicit 類型轉換運算子。所以直接輸入參數即可

$project 操作符

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

結果:你會發現StudentItems 被單獨提取出來

$unwind 操作符

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

結果:你會發現StudentItems 的每一項都抽出來與原來的文檔組成一個新的文檔

一般情況,$project和$unwind組合使用。比如提取出StudentItems 每一項組成一個文檔。例如

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

結果:

 $match 操作符

var items = collection.Aggregate<BsonDocument>(new[] {    new BsonDocument { { "$match", new BsonDocument("ClassName", "1年級") } }}).ToList();

結果:

$limit 操作符

$skip 操作符

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

結果:跳過前兩條之後,選擇前三條。例如:組合於分頁的應用

$group 操作符

$sum 操作符

var items = collection.Aggregate<BsonDocument>(new[] {    new BsonDocument {        { "$group", new BsonDocument {            { "_id", new BsonDocument("ClassName","$ClassName")},            { "count", new BsonDocument ("$sum",1) }}        }     }}).ToList();

結果:按年級分組,並且統計每組總行數

$sort 操作符

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

 

注意:操作符順序很重要,先後順序不同,會導致結果不一樣。

mongodb彙總查詢,筆記到這裡。

 

Mongodb進階查詢【二】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.