啥項目也跑不了統(tǒng)計套硼,作為開發(fā)甩鍋還沒甩出去瘾带。
查詢語句
最近兩個月內(nèi)訂單內(nèi)物品數(shù)量及訂單大小
order_export_1.js
var rows = db.order.aggregate([{
$addFields: {
itemCount: {
$function: {
body: function(types) {
var count = 0;
for (let i = 0; i < types.length; i++) {
if (types[i] == "item") {
count++;
}
}
return count;
},
// $relatedArtifacts是一個數(shù)組
args: ["$relatedArtifacts.type"],
lang: "js"
}
},
createDate: {
$function: {
body: function(createAt) {
return new Date(createAt);
},
args: ["$createAt"],
lang: "js"
}
}
}
},
{$match: {createDate: {$gt: new Date(new Date().getTime() - 10 * 30 * 24 * 60 * 60 * 1000)}}},
{
$project: { "_id": 1, "itemCount": 1, objectSize: { $bsonSize: "$$ROOT" } }
}, {
$sort: { "objectSize": -1 }
}]);
rows.forEach(function(row){
print(row._id+","+row.itemCount+","+row.objectSize);
});
4.0.0以下版本替代方案(沒有bsonSize函數(shù)不知道咋搞)
var rows = db.base_order.aggregate([{
$addFields: {
itemCount: {
$size: {
$filter: {
input: "$relatedArtifacts.type",
as: "type",
cond: { $eq: ["$$type", "item"] }
}
}
},
createSecond: {
$subtract: [{$divide: ["$createAt", 1000] }, {$divide: [{$mod: ["$createAt", 1000]}, 1000] }]
}
}
},
{$match: {createAt: {$gt: new Date().getTime() - 2 * 30 * 24 * 60 * 60 * 1000}}},
{
$project: { "_id": 1, "itemCount": 1 }
}, {
$sort: { "objectSize": -1 }
}]);
rows.forEach(function(row){
print(row._id+","+row.itemCount);
});
最近兩個月內(nèi)每分鐘訂單量
order_export_2.js
var rows = db.order.aggregate([
{
$addFields: {
createDate: {
$function: {
body: function(createAt) {
return new Date(createAt);
},
args: ["$createAt"],
lang: "js"
}
}
}
},
{$match: {createDate: {$gt: new Date(new Date().getTime() - 2 * 30 * 24 * 60 * 60 * 1000)}}},
{
$project: { date: { $dateToString: { format: '%Y-%m-%d %H:%M', date: '$createDate' } } },
},
{ $group: { _id: '$date', count: { $sum: 1 } } },
{ $project: { date: '$_id', _id: 0, count: 1 } },
{ $sort: { count: -1 } }
]);
rows.forEach(function(row){
print(row.date+","+row.count);
});
4.0.0以下版本替代方案
var rows = db.base_order.aggregate([
{
$addFields: {
createSecond: {
$subtract: [{$divide: ["$createAt", 1000] }, {$divide: [{$mod: ["$createAt", 1000]}, 1000] }]
}
}
},
{$match: {createAt: {$gt: new Date().getTime() - 2 * 30 * 24 * 60 * 60 * 1000}}},
{ $group: { _id: '$createSecond', count: { $sum: 1 } } },
{ $project: { second: '$_id', _id: 0, count: 1 } },
{ $sort: { count: -1 } }
]);
rows.forEach(function(row){
print(row.second+","+row.count);
});
導(dǎo)出命令
mongodb沒提供查詢結(jié)果csv導(dǎo)出的功能,把輸出重定向到文本將就熟菲。
mongo ${host}:${port}/${database} -u ${username} -p ${password} --authenticationDatabase=admin order_export_2.js > output2.csv