1. 掌握MongoDB 文档复杂查询
掌握MongoDB文档聚合查询
实验题目:
题目一:文档查询
题目二:聚合查询
实验要求:
1.1使用test数据库,并新建items集合
const MongoClient = require(‘mongodb’).MongoClient;
// 连接字符串
const uri =‘mongodb://localhost:27017’;
// 数据库名
const dbName = ‘test’;
// 集合名
const collectionName = ‘items’;
1.2执行操作
(async function () {
try {
const client = await MongoClient.connect(uri);
const db = client.db(dbName);
const collection = db.collection(collectionName);
// 插入数据
await collection.insertMany([
{"quantity":2,"price":5.0,"pnumber":"p003"},
{"quantity":2,"price":8.0,"pnumber":"p002"},
{"quantity":1,"price":4.0,"pnumber":"p002"},
{"quantity":2,"price":4.0,"pnumber":"p001"},
{"quantity":4,"price":10.0,"pnumber":"p003"},
{"quantity":10,"price":20.0,"pnumber":"p001"},
{"quantity":10,"price":20.0,"pnumber":"p003"},
{"quantity":5,"price":10.0,"pnumber":"p002"}
]);
1.3 查询插入结果
const insertedDocs = await collection.find({}).toArray();
console.log('插入结果:', insertedDocs);
1.4查询价格大于 5 的商品数据
const priceGreaterThan5Docs = await collection.find({ price: { $gt: 5 } }).toArray();
console.log('价格大于 5 的商品数据:', priceGreaterThan5Docs);
1.5查询 quantity 为 10 且价格大于等于 5 的商品数据
const specificDocs = await collection.find({ quantity: 10, price: { $gte: 5 } }).toArray();
console.log('quantity 为 10 且价格大于等于 5 的商品数据:', specificDocs);
2 聚合操作
2.1统计所有商品的数量(quantity 的总和)
const totalQuantity = await collection.aggregate([
{ $group: { _id: null, totalQuantity: { $sum: '$quantity' } } }
]).toArray();
console.log('所有商品数量总和:', totalQuantity[0].totalQuantity);
2.2 通过产品类型进行分组并统计卖出数量
const groupedByPnumber = await collection.aggregate([
{ $group: { _id: '$pnumber', soldQuantity: { $sum: '$quantity' } } }
]).toArray();
console.log('按产品类型分组统计:', groupedByPnumber);
2.3 通过不同产品类型分组查询卖出最多的订单详情
const mostSoldByPnumber = await collection.aggregate([
{ $group: { _id: '$pnumber', mostSoldDoc: { $first: '$$ROOT' } } },
{ $sort: { 'quantity': -1 } }
]).toArray();
console.log('按产品类型分组卖出最多的订单详情:', mostSoldByPnumber);
2.4通过不同产品类型分组统计各个产品数量并获取最大数量
const groupedWithMaxQuantity = await collection.aggregate([
{ $group: { _id: '$pnumber', productQuantity: { $sum: '$quantity' } } },
{ $sort: { productQuantity: -1 } },
{ $limit: 1 }
]).toArray();
console.log('按产品类型分组最大数量:', groupedWithMaxQuantity[0].productQuantity);
} catch (err) {
console.error(‘出错了:’, err);
} finally {
client.close();
}
})();