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);
});