【HH原创】MangoDB 的 aggregate 操作

Aggregation Pipeline

 

聚合操作中的 $match 条件匹配

// 两个匹配叠加,必须同时符合两条 $match 规则
{ $match: { year: 2014 } },
{ $match: { status: "A" } }
// 两个匹配叠加,必须同时符合两条 $match 规则
{ $match: { $and: [ { "year" : 2014 }, { "status" : "A" } ] } }
// 两个匹配叠加,只需要满足任意一条 $match 规则
{ $match: { $or: [ { "year" : 2014 }, { "status" : "A" } ] } }

 

$sort + $skip + $limit

{ $sort: { age : -1 } },
{ $skip: 10 },
{ $limit: 5 }

 

下面是本人实际操作 MangoDB 中的应用示例:

// 某日志库 PV 统计数据

function padLeft(num, n) {
  return (Array(n).join(0) + num).slice(-n);
}


var list = [];
for (var i = 0; i < 7; i++) {
  var today = new Date('2018-08-20');
  var month = today.getMonth() + 1;
  var day = today.getDate();
  
  today.setDate(day + i);
  month = today.getMonth() + 1;
  day = today.getDate();
  
  var dbName = today.getFullYear() + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day) + '_t_ts_page';
  print(dbName);
  
  
  db[dbName].aggregate([
	{ $match: { $or: [ { "platform" : "siteA" }, { "platform" : "siteB" } ] } },
	{ $group: {"_id": { "platform" : "$platform", "refUrl": "$refUrl"}, "count":{$sum:1}} },
	{ $project : {"_id": 0, "platform" : "$_id.platform", "refUrl" : "$_id.refUrl", "count" : 1}},
	{ $sort: {platform: -1, refUrl: 1} }
  ]).forEach(function (item) {
  	list.push(item);
  });

};

var result = [];
list.forEach(function(item){
  var isDuplicate = false;
  result.forEach(function(x){
    if (item.refUrl == x.refUrl){
      isDuplicate = true;
      x.count += item.count;
    }
  });
  
  if (!isDuplicate){
    result.push(item);
  }
  
  
//  print(item.platform + '    ' + padLeft(item.count, 5) + '  ' + item.refUrl);
//  print(item.platform + '    ' + item.count + '  ' + item.refUrl);
});


result.forEach(function(item){
  print(item.platform + ' ' + item.count + ' ' + item.refUrl);
});

 

 

 

转载于:https://my.oschina.net/u/943746/blog/1930983

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值