由于项目需要使用到MongoDB,花了一些时间来练习Mongo的聚合操作,实际项目中是使用Spring-data/mongodb,这里先写sql。
整个练习是基于某博主的一个Mongodb练习小项目,其Collection文档结构如下:
{
"_id" : ObjectId("5af2e8f2064079ef797e22a7"),
"title" : "title_10",
"url" : "url_10",
"ptimes" : "2014-02-12 20:11:53",
"ptime" : NumberLong(1392207113828),
"pdate" : ISODate("2014-02-12T12:11:53.828Z"),
"pmedia" : "publishMedia_10",
"area" : "10240502",
"ckey" : [
"22",
"26",
"A102",
"A202",
"A101",
"A201"
],
"eval" : 0,
"mpro" : 1,
"mtype" : 10,
"level" : 7
}
可自行添加多条记录
group:
db.news.group({
key:{"level":1},
initial:{"count":0},
$reduce:function(doc,out){out.count++;},
$finalize:function(out){return out;}
})
aggregate:
db.news.aggregate([{$group:{
_id: null
, sumCount:{
$sum:"$eval"
}}}])
db.news.aggregate([{$group:{
_id: null
, sumCount:{
$sum:"$level"
}}}])
db.news.aggregate([{$group:{_id: "$eval", total:{$sum:"$level"}}},{$limit:1}])
db.news.aggregate([{$group:{_id: "$eval", total:{$sum:"$level"}}}, {$sort:{_id:-1}}])
db.news.aggregate([{$match:{area: "1024"}}])
db.news.aggregate([{$project:{title:1, ptimes:1, _id:0, url:1}}])
db.news.aggregate([{$project:{"retitle":"$title", "reptimes":"$ptimes", "reurl":"$url", _id:0}}])
db.news.aggregate([{$project:{"total":{$add:["$mtype","$level"]}}}])
db.news.aggregate([{$project:{total:{$add:["$mtype","$level"]}}}])
db.news.aggregate([{$project:{total:{$subtract:[{$add:["$mtype","$level"]},"$mpro"]}}}])
db.news.aggregate([{$project:{chenfa:{$multiply:["$level","$mtype","$mpro"]}}}])
db.news.aggregate([{$project:{divi:{$divide:["$mtype","$mpro"]}}}])
db.news.aggregate([{$project:{"retitle":"$title","reptimes":"$ptimes","rearea":"$area","relevel":"$level"}},{$match:{"relevel":{$lte: 2},"reptimes":{$gte:"2014-02-12 20:11:53" , $lte:"2014-03-12 20:11:53"}}}])
db.news.aggregate([{$project:{"retitle":"$title","reptimes":"$ptimes","rearea":"$area","relevel":"$level"}},{$match:{"relevel":{$lte: 2},"reptimes":{$gte:"2014-02-12 20:11:53",$lte:"2014-03-12 20:11:53"}}},{$group: {_id:null,count:{$sum:1}}}])
以上sql基于$project、$match、$group等常用筛选、聚合操作,如有帮助,不甚荣幸。。。