MongoDB的索引与聚合

一、实验目的

  1. 理解索引的概念及其在MongoDB中的重要性和作用。

  2. 学习如何选择适合建立索引的字段。

  3. 掌握如何创建、删除索引以及如何强制使用索引。

  4. 熟悉MongoDB的聚合框架和MapReduce工具,以及简单聚合命令的使用。

二、实验环境准备

  1. JAVA环境准备:确保Java Development Kit (JDK) 已安装并配置好环境变量。

  2. Hadoop环境准备:安装并配置Hadoop环境,确保Hadoop的各个组件可以在伪分布式模式下运行。

三、实验教材参考

《大数据存储》,谭旭,人民邮电出版社,2022,ISBN 978-7-115-59414-3。

四、实验内容与步骤

1、索引操作

  1. 创建文档并插入数据

    db.createCollection("studata")
    db.studata.insert({
    name:"Alice",
    age:22,
    score:85,
    class:"Physics"
    })

复制代码
db.studata.insert([
  { name: "Alice", age: 22, score: 85, class: "Physics" },
{ name: "Bob", age: 21, score: 78, class: "Chemistry" },
{ name: "Charlie", age: 23, score: 92, class: "Physics" },
{ name: "David", age: 20, score: 65, class: "Mathematics" }
]);
  1. 创建单字段索引

db.studata.createIndex({age:1})

  1. 创建复合索引

db.studata.createIndex({ class: 1, score: -1 });

  1. 创建文本索引

db.studata.createIndex({ name: "text" });

  1. 查看查询计划并评估单字段索引效果

db.studata.find({ age: 22 }).explain("executionStats");

  1. 查看查询计划并评估复合索引效果

db.studata.find({ class: "Physics", score: { $gt: 80 } }).explain("executionStats");

  1. 查看查询计划并评估文本索引效果

db.studata.find({ text: { search: "Alice" } }).explain("executionStats");

  1. 删除索引

删除单字段索引

db.studata.dropIndex({ age: 1 });

删除复合索引

db.studata.dropIndex({ class: 1, score: -1 });

2、聚合工具

  1. 统计文档数量

db.studata.aggregate([

{ $match: { class: "Physics" } },

{ group: { _id: null, total_students: { sum: 1 } } }

]);

  1. 获取字段唯一值

db.studata.distinct("class");

  1. 分组统计

db.studata.aggregate([

{ $group: {

_id: "$class",

total_students: { $sum: 1 },

average_score: { avg: "score" }

} }

]);

  1. 排序和限制

按分数降序排列,取前5名

db.studata.aggregate([

{ $sort: { score: -1 } },

{ $limit: 5 }

]);

  1. 使用MapReduce处理复杂的聚合任务

db.studata.mapReduce(

function() { emit(this.class, this.score); },

function(key, values) { return Array.sum(values); },

{

out: "class_total_scores"

}

);

查看 MapReduce 结果

db.class_total_scores.find();

相关推荐
马克Markorg7 小时前
常见的向量数据库和具有向量数据库能力的数据库
数据库
Coder_Boy_9 小时前
技术让开发更轻松的底层矛盾
java·大数据·数据库·人工智能·深度学习
helloworldandy9 小时前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python
数据知道11 小时前
PostgreSQL 故障排查:如何找出数据库中最耗时的 SQL 语句
数据库·sql·postgresql
qq_124987075311 小时前
基于SSM的动物保护系统的设计与实现(源码+论文+部署+安装)
java·数据库·spring boot·毕业设计·ssm·计算机毕业设计
枷锁—sha11 小时前
【SRC】SQL注入WAF 绕过应对策略(二)
网络·数据库·python·sql·安全·网络安全
Coder_Boy_11 小时前
基于SpringAI的在线考试系统-考试系统开发流程案例
java·数据库·人工智能·spring boot·后端
Gain_chance11 小时前
35-学习笔记尚硅谷数仓搭建-DWS层最近n日汇总表及历史至今汇总表建表语句
数据库·数据仓库·hive·笔记·学习
此生只爱蛋12 小时前
【Redis】主从复制
数据库·redis
马猴烧酒.12 小时前
【面试八股|JAVA多线程】JAVA多线程常考面试题详解
java·服务器·数据库