Aggregation Pipeline日誌
聚合操做中的 $match 條件匹配code
// 兩個匹配疊加,必須同時符合兩條 $match 規則 { $match: { year: 2014 } }, { $match: { status: "A" } }
// 兩個匹配疊加,必須同時符合兩條 $match 規則 { $match: { $and: [ { "year" : 2014 }, { "status" : "A" } ] } }
// 兩個匹配疊加,只須要知足任意一條 $match 規則 { $match: { $or: [ { "year" : 2014 }, { "status" : "A" } ] } }
$sort + $skip + $limitorm
{ $sort: { age : -1 } }, { $skip: 10 }, { $limit: 5 }
下面是本人實際操做 MangoDB 中的應用示例:blog
// 某日誌庫 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); });