Databases 26 min read

Master MongoDB: From Basics to Advanced Operations

This comprehensive guide introduces NoSQL concepts, classifies non‑relational databases, explains why MongoDB is suited for loosely structured data, walks through Windows and Linux installations, demonstrates using Robo 3T, and covers all CRUD operations, queries, updates, deletions, and data de‑duplication with practical code examples.

Ops Development Stories
Ops Development Stories
Ops Development Stories
Master MongoDB: From Basics to Advanced Operations

1 进入MongoDB的世界

随着大数据时代的到来,数据急速增长,关系型数据库(SQL)已难以满足需求,非关系型数据库(NoSQL)因此兴起,MongoDB 作为分布式文档型数据库在 2009 年掀起去 SQL 的浪潮。

1.1 非关系型数据库的分类及特点

键值数据库:代表有 Redis、Flare,读写性能极高,适合高访问负载。

文档型数据库:代表有 MongoDB、CouchDB,存储灵活,字段可随意增删,适用于各种网络应用。

列存储数据库:代表有 Cassandra、HBase,查询速度快,扩展性强,适合分布式文件存储。

图数据库:代表有 InfoGrid、Neo4J,适用于社交网络和推荐系统的关系图谱。

1.2 MongoDB适合做什么

MongoDB 适合存储大量关联性不强的数据,采用库‑集合‑文档‑字段的层次结构,免预定义表结构,字段可随意变动,并发写入速度远超传统关系型数据库。

1.3 从文件到MongoDB数据库

少量数据可用记事本或 Excel 保存,但当数据量超过百万行时,需要使用数据库。MongoDB 能保存海量数据并支持灵活的字段结构。

2 MongoDB快速入门

本节介绍 MongoDB 的安装、基本语法、Robo 3T 图形化管理工具以及 Python 操作示例。

2.1 MongoDB和SQL术语对比

SQL 与 MongoDB 术语对比如下:

<code>SQL          MongoDB
表(Table)   集合(Collection)
行(Row)      文档(Document)
列(Col)      字段(Field)
主键(Primary Key)  对象ID(ObjectId)
索引(Index)   索引(Index)
嵌套表(Embedded Table)  嵌入式文档(Embedded Document)
数组(Array)   数组(Array)</code>

2.2 安装MongoDB

2.2.1 在Windows中安装

访问 MongoDB 官网下载页面,点击 “DOWNLOAD (msi)” 按钮。

双击下载的文件,选择 “Custom” 安装方式。

修改安装路径为 D:\MongoDB\Server\,完成安装。

安装完成后可在 D:\MongoDB\Server\4.2\bin\ 中看到 mongod.cfg 配置文件。

日志路径为 D:\MongoDB\Server\4.2\log。

2.2.2 在Linux中安装(以 CentOS 7.6 为例)

创建 yum 源文件并添加以下内容:

<code>[root@localhost]# cd /etc/yum.repos.d
[root@localhost yum.repos.d]# vim mongodb-org-4.2.repo
[mongodb-org]
name=MongoDB Repository
baseurl=http://mirrors.aliyun.com/mongodb/yum/redhat/7Server/mongodb-org/4.2/x86_64/
gpgcheck=0
enabled=1</code>

更新系统包:

<code>[root@localhost yum.repos.d]# yum update</code>

安装 MongoDB:

<code>[root@localhost yum.repos.d]# yum -y install mongodb-org</code>

查看安装位置:

<code>[root@localhost yum.repos.d]# whereis mongod
mongod: /usr/bin/mongod /etc/mongod.conf /usr/share/man/man1/mongod.1</code>

修改配置文件,将

bindIp: 127.0.0.1

改为

bindIp: 0.0.0.0

,然后启动服务:

<code>[root@localhost]# systemctl start mongod.service</code>

设置开机自启:

<code>[root@localhost]# systemctl enable mongod.service</code>

若需外网访问,关闭防火墙并在

/etc/sysconfig/iptables

中添加:

<code>-A INPUT -m state --state NEW -m tcp -p tcp --dport 27017 -j ACCEPT</code>

3 MongoDB的图形化管理软件——Robo 3T

Robo 3T 是跨平台的 MongoDB 管理工具,提供直观的图形界面。

3.1 安装

下载地址:https://robomongo.org/download(免费开源)。

安装过程与普通软件相同。

3.2 用Robo 3T连接MongoDB

打开软件,点击左上角 “Create”。

填写连接名称,若本机运行则无需修改其他字段,点击 “Save”。

点击 “Connect” 完成连接。

3.3 认识Robo 3T的界面

界面分为三大区域:

数据库列表区(A 区),用于选择数据库和集合。

数据展示区(B 区),用于显示查询结果。

命令执行区(C 区),用于编写并运行 MongoDB 命令。

4 MongoDB的基本操作

增、查、改、删是所有数据库的核心功能,以下示例均在 Robo 3T 的 C 区执行。

4.1 创建数据库与集合,写入数据

创建名为

chapter_1

的数据库及其集合。

使用

insertOne()

插入单条 JSON 文档。

使用

insertMany()

批量插入多个文档。

<code>db.getCollection('example_data_1').insertOne({"name": "王小二", "age": 17, "address": "浙江"})</code>
<code>data_list = [
   {'name': '赵小三','age':20,'address':'北京'},
   {'name': '钱小四','age':21,'address':'上海'},
   {'name': '孙小五','age':20,'address':'山东'},
   {'name': '李小六','age':23,'address':'河北'},
   {'name': '欧阳小七','age':24,'address':'杭州'}
]
db.getCollection('example_data_1').insertMany(data_list)</code>

4.2 查询数据

查询所有文档:

db.getCollection('example_data_1').find()

查询特定字段值:

db.getCollection('example_data_1').find({'age': 23})

范围查询:

db.getCollection('example_data_1').find({'age': {'$gte': 23}})

投影字段:

db.getCollection('example_data_1').find({}, {'name':1,'age':1,'_id':0})

计数:

db.getCollection('example_data_1').find({'age':{'$gt':21}}).count()

限制返回条数:

db.getCollection('example_data_1').find().limit(4)

排序:

db.getCollection('example_data_1').find({'age':{'$gt':21}}).sort({'age':-1})

4.3 修改数据

使用

updateOne()

updateMany()

,配合

$set

修改字段。

<code>db.getCollection('example_data_1').updateMany({'name':'王小六'},{'$set':{'address':'苏州','work':'DBA'}})</code>

4.4 删除数据

先查询再删除,避免误删。

<code>db.getCollection('example_data_1').deleteMany({'hello':'world'})</code>
建议使用“假删除”方式,即添加 deleted 字段标记删除状态。

4.5 数据去重

使用

distinct()

获取字段唯一值。

<code>db.getCollection('example_data_1').distinct('age')
db.getCollection('example_data_1').distinct('age',{'age':{'$gte':20}})</code>
databaseCRUDInstallationmongodbNoSQLRobo 3T
Ops Development Stories
Written by

Ops Development Stories

Maintained by a like‑minded team, covering both operations and development. Topics span Linux ops, DevOps toolchain, Kubernetes containerization, monitoring, log collection, network security, and Python or Go development. Team members: Qiao Ke, wanger, Dong Ge, Su Xin, Hua Zai, Zheng Ge, Teacher Xia.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.