啥项目也跑不了统计,作为开发甩锅还没甩出去。
查询语句
最近两个月内订单内物品数量及订单大小
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是一个数组
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函数不知道咋搞)
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);
});
最近两个月内每分钟订单量
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);
});
导出命令
mongodb没提供查询结果csv导出的功能,把输出重定向到文本将就。
mongo ${host}:${port}/${database} -u ${username} -p ${password} --authenticationDatabase=admin order_export_2.js > output2.csv
网友评论