第23章:MongoDB-聚合操作--聚合命令

原文链接: http://www.cnblogs.com/Lucky-stars/p/10555313.html
①count()

范例:统计students表中的数据量

db.students.count();

范例:模糊查询

db.students.count("name":/张/i);

 

②distinct()

范例:求某个字段不同的值

db.students.distinct("name");

db.runCommand({"distinct":"students","key":"name"});

③group()

key: 用于指定要分组的键

initial: 对于分组统计的字段设置键名和初始值

reduce: 循环每个分组中的每个文档,一组循环完了会继续下一组

condition:用于分组前筛选掉不满足条件的文档

finalize: 用于对分组后的结果进一步处理,每组都会调用finalize

 

db.articles.group({

   "key": {"author": true},

   "initial": {"sum": 0},

   "reduce": function(doc, prev) {

       if(doc.like > 10) {

           prev.sum += 1;

       }

   }

})

[

       {

               "author" : "zhangsan",

               "sum" : 2

       },

       {

               "author" : "lisi",

               "sum" : 2

       },

       {

             "author" : "mengday",

               "sum" : 0

       }

]

 

db.articles.group({

   "key": {"author": true},

   "initial": {"sum": 0},

   "reduce": function(doc, prev) {

       if(doc.like > 10) {

           prev.sum += 1;

       }

   },

   "condition":{"author": {"$ne": "mengday"}}

})

[

       {

               "author" : "zhangsan",

               "sum" : 2

       },

       {

               "author" : "lisi",

          "sum" : 2

       }

]

 

db.articles.group({

   "key": {"author": true},

   "initial": {"sum": 0},

   "reduce": function(doc, prev) {

       if(doc.like > 10) {

         prev.sum += 1;

       }

   },

   "condition":{"author": {"$ne": "mengday"}},

   "finalize": function(doc){

       if(doc.author == "zhangsan"){

           delete doc

       }

   }

})

[

       {

               "author" : "zhangsan",

               "sum" : 3

       },

       {

               "author" : "lisi",

               "sum" : 2

       }

]

 

范例:查询所有年龄大于等于19岁的学生信息,并且按照年龄分组

db.runCommand({"group":{

    "ns":"students",//集合

    "key":{"age":true},//按照age分组

    "initial":{"count":0},//默认数量为0

    "condition":{"age":{"$gt":19}},//条件

    "$reduce":function(doc,prev){//完成后的操作

           prev.count ++;

      }

}});

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/Lucky-stars/p/10555313.html

猜你喜欢

转载自blog.csdn.net/weixin_30670151/article/details/94805998