应用场景:
根据特定条件分组处理数据,类似于SQL中的GROUP BY查询语句,mongoDB中的group功能更为强大,自由度更高。
使用语法:
db.runCommand( { group: { ns: <namespace>, key: <key>, $reduce: <reduce function>, // $keyf: <key function>, cond: <query> } } )
其中:
ns:集合名词
key:分组的依据
$reduce:是一个函数,该函数会在符合条件的每个文档上执行,系统会给该函数传递两个参数,当前文档和累加器文档(本组当前该函数执行结果)
cond:查询条件,满足此条件的文档才会被group分组和累加
$keyf:key生成函数,系统会给该函数传递一个参数,即当前文档,返回值为对象,此参数和key参数互斥
测试数据:
group查询示例:
1.常规查询
查询内容:以author分组,查询每个author的累计阅读次数
db.runCommand( { group: { ns: 'readData', key: { author: 1 }, $reduce: function ( curr, result ) { result.read_times+=curr.read_times }, initial: { read_times:0 } } } )
查询结果:
{ "retval" : [ { "author" : "Jim", "read_times" : 64.0 }, { "author" : "Tom", "read_times" : 127.0 } ], "count" : NumberLong(4), "keys" : NumberLong(2), "ok" : 1.0 }
其中:
retval:查询结果
count:满足条件文档数
keys:分组数
2.含条件查询
查询内容:以author分组,查询category为database的每个author的累计阅读次数
db.runCommand( { group: { ns: 'readData', key: { author: 1 }, cond:{category:"database"}, $reduce: function ( curr, result ) { result.read_times+=curr.read_times }, initial: { read_times:0 } } } )
查询结果:
{ "retval" : [ { "author" : "Jim", "read_times" : 64.0 } ], "count" : NumberLong(2), "keys" : NumberLong(1), "ok" : 1.0 }
3.key由函数生成
查询内容:以author分组,查询每个author的累计阅读次数
db.runCommand( { group: { ns: 'readData', "$keyf": function(cur){ return {"author":cur.author}; }, $reduce: function ( curr, result ) { result.read_times+=curr.read_times }, initial: { read_times:0 } } } )
查询结果:
{ "retval" : [ { "author" : "Jim", "read_times" : 64.0 }, { "author" : "Tom", "read_times" : 127.0 } ], "count" : NumberLong(4), "keys" : NumberLong(2), "ok" : 1.0 }