MongoDB 是一款非关系型数据库,在前端开发中使用广泛。除了基本的增删改查外,MongoDB 还提供了丰富的数据统计和报表生成功能,能够帮助开发人员更好地理解和分析数据,为业务决策提供支持。
环境准备
在开始本文的实践示例前,请确保你已经正确安装了 MongoDB 数据库,并且了解了 MongoDB 的基础用法和语法,如果还不了解 MongoDB,可以参考官方文档学习。
数据统计
MongoDB 提供了丰富的数据统计功能,包括计数、求和、平均值、最大值、最小值、分组统计等常见的统计操作,下面我们分别介绍它们的使用方法。
计数
计数是 MongoDB 最基本的统计操作,它能够统计集合中满足条件的文档数量,如下所示:
db.collection.count(query)
其中,query 表示查询条件,如果不传递该参数,则返回集合中所有文档的数量。
示例代码:
// www.javascriptcn.com code example
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@<cluster>/<database>?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(async err => {
const collection = client.db("<database>").collection("<collection>");
const total = await collection.count();
console.log('总记录数:', total);
client.close();
});求和
求和是 MongoDB 统计中常用的操作,它能够计算集合中指定字段的累加值,如下所示:
db.collection.aggregate([
{ $match: { <query> } },
{ $group: { _id: null, total: { $sum: "$<field>" } } }
])其中,query 表示查询条件,field 表示要求和的字段。
示例代码:
// www.javascriptcn.com code example
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@<cluster>/<database>?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(async err => {
const collection = client.db("<database>").collection("<collection>");
const result = await collection.aggregate([
{ $match: {} },
{ $group: { _id: null, total: { $sum: "$age" } } }
]).toArray();
console.log('年龄总和:', result[0].total);
client.close();
});平均值
平均值是 MongoDB 统计中常用的操作,它能够计算集合中指定字段的平均值,如下所示:
db.collection.aggregate([
{ $match: { <query> } },
{ $group: { _id: null, avg: { $avg: "$<field>" } } }
])其中,query 表示查询条件,field 表示要求平均值的字段。
示例代码:
// www.javascriptcn.com code example
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@<cluster>/<database>?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(async err => {
const collection = client.db("<database>").collection("<collection>");
const result = await collection.aggregate([
{ $match: {} },
{ $group: { _id: null, avg: { $avg: "$age" } } }
]).toArray();
console.log('年龄平均值:', result[0].avg);
client.close();
});最大值
最大值是 MongoDB 统计中常用的操作,它能够计算集合中指定字段的最大值,如下所示:
db.collection.aggregate([
{ $match: { <query> } },
{ $group: { _id: null, max: { $max: "$<field>" } } }
])其中,query 表示查询条件,field 表示要求最大值的字段。
示例代码:
// www.javascriptcn.com code example
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@<cluster>/<database>?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(async err => {
const collection = client.db("<database>").collection("<collection>");
const result = await collection.aggregate([
{ $match: {} },
{ $group: { _id: null, max: { $max: "$age" } } }
]).toArray();
console.log('最大年龄:', result[0].max);
client.close();
});最小值
最小值是 MongoDB 统计中常用的操作,它能够计算集合中指定字段的最小值,如下所示:
db.collection.aggregate([
{ $match: { <query> } },
{ $group: { _id: null, min: { $min: "$<field>" } } }
])其中,query 表示查询条件,field 表示要求最小值的字段。
示例代码:
// www.javascriptcn.com code example
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@<cluster>/<database>?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(async err => {
const collection = client.db("<database>").collection("<collection>");
const result = await collection.aggregate([
{ $match: {} },
{ $group: { _id: null, min: { $min: "$age" } } }
]).toArray();
console.log('最小年龄:', result[0].min);
client.close();
});分组统计
分组统计是 MongoDB 统计中常用的操作,它能够根据指定字段对集合中的文档进行分组,并统计指定字段的值,如下所示:
db.collection.aggregate([
{ $match: { <query> } },
{ $group: { _id: "$<group_field>", total: { $sum: "$<count_field>" } } },
{ $sort: { total: -1 } }
])其中,query 表示查询条件,group_field 表示分组字段,count_field 表示要统计的字段。
示例代码:
// www.javascriptcn.com code example
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@<cluster>/<database>?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(async err => {
const collection = client.db("<database>").collection("<collection>");
const result = await collection.aggregate([
{ $match: {} },
{ $group: { _id: "$gender", total: { $sum: 1 } } },
{ $sort: { total: -1 } }
]).toArray();
console.log('男生人数:', result[0].total);
console.log('女生人数:', result[1].total);
client.close();
});报表生成
报表生成是 MongoDB 统计的进一步应用,可以根据统计结果生成数据报表,下面我们使用第三方库 ag-grid 和 html-pdf 来实现一个简单的 PDF 报表生成示例。
首先,我们需要安装 ag-grid 和 html-pdf:
npm install ag-grid-community npm install html-pdf
然后,我们来实现一个按年龄分组的 PDF 报表生成功能,过程如下:
- 从 MongoDB 中查询年龄分组统计数据。
- 创建一个带有表格布局的 HTML 文件。
- 使用
ag-grid将查询结果填充到 HTML 表格中。 - 使用
html-pdf将 HTML 文件转换为 PDF 格式。 - 将 PDF 文件保存到本地。
示例代码:
// www.javascriptcn.com code example
const MongoClient = require('mongodb').MongoClient;
const AgGrid = require('ag-grid-community');
const pdf = require('html-pdf');
const uri = "mongodb+srv://<username>:<password>@<cluster>/<database>?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
(async () => {
// 查询年龄分组统计数据
const collection = client.db("<database>").collection("<collection>");
const result = await collection.aggregate([
{ $group: { _id: "$age", total: { $sum: 1 } } },
{ $sort: { _id: 1 } }
]).toArray();
// 创建 HTML 表格
const html = `
<html>
<head>
<style>
table { border-collapse: collapse; }
th, td { border: 1px solid black; padding: 5px; }
</style>
</head>
<body>
<h1>年龄分组统计结果</h1>
<div id="myGrid" style="height: 500px;"></div>
<script src="https://unpkg.com/ag-grid-community/dist/ag-grid-community.min.js"></script>
<script>
var columnDefs = [
{ headerName: "年龄", field: "age" },
{ headerName: "人数", field: "total" }
];
var rowData = ${JSON.stringify(result)};
var gridOptions = {
columnDefs: columnDefs,
rowData: rowData
};
var gridDiv = document.querySelector('#myGrid');
new agGrid.Grid(gridDiv, gridOptions);
</script>
</body>
</html>
`;
// 转换为 PDF 格式
const options = { format: 'A4' };
pdf.create(html, options).toFile('./result.pdf', (err, res) => {
if (err) return console.log(err);
console.log(res);
});
client.close();
})();执行以上代码后,将在当前目录下生成一个名为 result.pdf 的 PDF 文件,打开即可看到年龄分组统计结果。此外,你还可以根据自己的需求,修改 HTML 和 CSS 样式,生成更加美观的报表。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67c9b8c0e46428fe9e182fc2