您好,登錄后才能下訂單哦!
日期分組 db.msds_acce***ecord.group({ keyf : function(doc){ var date = new Date(doc.addtime); var dateKey = ""+date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate(); return {'day':dateKey}; //33}, initial : {"count":0}, reduce : function Reduce(doc, out) { if(doc.url){ out.count +=1; } } });
先插入測試數據:
for(var i=1; i<20; i++){
var num=i%6;
db.test.insert({_id:i,name:"user_"+i,age:num});
}
1.普通分組查詢
db.test.group({key:{age:true},initial:{num:0},$reduce:function(doc,prev){
prev.num++
}});
db.runCommand({group:
{
ns:"test",
key:{age:true},
initial:{num:0},
$reduce:function(doc,prev){
prev.num++}
}
});
2.篩選后再分組
db.test.group({key:{age:true},initial:{num:0},$reduce:function(doc,prev){
prev.num++
},
condition:{age:{$gt:2}}
});
db.runCommand({group:
{
ns:"test",
key:{age:true},
initial:{num:0},
$reduce:function(doc,prev){
prev.num++},
condition:{age:{$gt:2}}
}
});
普通的$where查詢:
db.test.find({$where:function(){
return this.age>2;
}
});
group聯合$where查詢
db.test.group({key:{age:true},initial:{num:0},$reduce:function(doc,prev){
prev.num++
},
condition:{$where:function(){
return this.age>2;
}
}
});
3.使用函數返回值分組
//注意,$keyf指定的函數一定要返回一個對象
db.test.group({$keyf:function(doc){return {age:doc.age};},initial:{num:0},$reduce:function(doc,prev){
prev.num++
}
});
db.runCommand({group:
{
ns:"test",
$keyf:function(doc){return {age:doc.age};},
initial:{num:0},
$reduce:function(doc,prev){
prev.num++}
}
});
4.使用終結器
db.test.group({$keyf:function(doc){return {age:doc.age};},initial:{num:0},$reduce:function(doc,prev){
prev.num++
},
finalize: function(doc){ doc.count=doc.num;delete doc.num; }
});
db.runCommand({group:
{
ns:"test",
$keyf:function(doc){return {age:doc.age};},
initial:{num:0},
$reduce:function(doc,prev){
prev.num++},
finalize: function(doc){ doc.count=doc.num;delete doc.num; }
}
});
有關MapReduce
//首先插入測試數據
for(var i=1;i<21;i++)
{
db.test.insert({_id:i,name:'mm'+i});
}
//進行mapreduce
db.runCommand(
{
mapreduce:'test',
map:function(){emit(this.name.substr(0,3),this);},
reduce:function(key,vals){return vals[0];}, //注意:vals是一個Object對象而不是數組
out:'wq'
});
注意:
1.mapreduce是根據map函數里調用的emit函數的第一個參數來進行分組的
2.僅當根據分組鍵分組后一個鍵匹配多個文檔,才會將key和文檔集合交由reduce函數處理。例如:
db.runCommand(
{
mapreduce:'test',
map:function(){emit(this.name.substr(0,3),this);},
reduce:function(key,vals){return 'wq';},
out:'wq'
});
執行mapreduce命令后,再查看wq表數據:
db.wq.find()
{ "_id" : "mm1", "value" : "wq" }
{ "_id" : "mm2", "value" : "wq" }
{ "_id" : "mm3", "value" : { "_id" : 3, "name" : "mm3" } }
{ "_id" : "mm4", "value" : { "_id" : 4, "name" : "mm4" } }
{ "_id" : "mm5", "value" : { "_id" : 5, "name" : "mm5" } }
{ "_id" : "mm6", "value" : { "_id" : 6, "name" : "mm6" } }
{ "_id" : "mm7", "value" : { "_id" : 7, "name" : "mm7" } }
{ "_id" : "mm8", "value" : { "_id" : 8, "name" : "mm8" } }
{ "_id" : "mm9", "value" : { "_id" : 9, "name" : "mm9" } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。