【无标题】

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();
}
})();

  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值