简单介绍
MongoDB 是一款高性能的 NoSQL 文档型数据库,使用 BSON(二进制 JSON)格式存储数据,适合存储大规模、高并发的非结构化数据,常用于大数据、日志存储和微服务架构中。
安装
windows直接去官网下载安装包,按照提示安装即可。
Linux 安装脚本如下(以 Ubuntu 为例):官方教程
# 查看系统版本,选择对应的安装脚本
hostnamectl
# 第一步:导入公钥
sudo apt-get install gnupg curl
curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg \
--dearmor
# 第二步:创建列表文件
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
# 第三步:更新软件包列表
sudo apt-get update
# 第四步:安装 MongoDB
sudo apt-get install -y mongodb-org
简单使用
服务管理
# 启动服务
sudo systemctl start mongod
# 停止服务
sudo systemctl stop mongod
# 重启服务
sudo systemctl restart mongod
# 查看服务状态
sudo systemctl status mongod
# 开机自启动
sudo systemctl enable mongod
端口及数据位置
编辑 /etc/mongod.conf
# 数据位置(修改位置后,新的文件夹归属需为 mongodb,权限值755)
storage:
dbPath: /var/lib/mongodb
# 端口及连接设置(原127.0.0.1仅允许本地连接)
net:
port: 27017
bindIp: 0.0.0.0
# 安全设置(默认关闭,可在配置了管理员后开启)
security:
authorization: enabled
开放端口
# 检查防火墙
sudo ufw status
# 开放端口
sudo ufw allow 27017/tcp
# 重新加载防火墙
sudo ufw reload
添加管理员
通过命令行 mongosh
或 Windows平台下 MongoDB Compass
连接,执行以下sql命令
use admin
db.createUser({
user: "admin",
pwd: "123456",
roles: [{ role: "root", db: "admin" }]
})
MongoDB 简单语法
# 连接数据库
mongosh --host 192.168.1.100 --port 27017 -u user -p password --authenticationDatabase admin database
# 切换数据库
use database
# 查看数据库列表
show dbs
# 查看当前数据库
db
# 查看用户
show users
# 查看角色
show roles
# 添加用户
db.createUser({
user: "user",
pwd: "123456",
roles: [{ role: "readWrite", db: "database" }]
})
# 删除用户
db.dropUser("user")
# 查看集合
show collections
# 添加集合
db.createCollection("collection")
# 删除集合
db.<collection>.drop()
# 具体记录的修改,基本上都是一个json对象
# 针对过滤条件query,其json值可以是一个带条件操作符的json对象,可嵌套
# 查看文档
db.<collection>.find(query)
db.<collection>.findOne(query)
db.<collection>.findMany(query)
# 添加文档
db.<collection>.insertOne({})
db.<collection>.insertMany([{}, {}])
# 更新文档
#upsert: true:如果找不到匹配的文档,则创建一个新文档
#multi: true:更新所有匹配的文档,默认只更新第一个
db.myCollection.updateOne(query, { <更新操作符>: { ... } }, { upsert: <boolean>, multi: <boolean> })
# 删除文档
db.<collection>.deleteOne({})
db.<collection>.deleteMany({})
条件操作符
类别 | 操作符 | 描述 | 示例 |
---|---|---|---|
比较操作符 | $eq |
匹配字段值等于指定值的文档 | db.users.find({ age: { $eq: 25 } }) |
$ne |
匹配字段值不等于指定值的文档 | db.users.find({ age: { $ne: 25 } }) |
|
$gt |
匹配字段值大于指定值的文档 | db.users.find({ age: { $gt: 25 } }) |
|
$gte |
匹配字段值大于等于指定值的文档 | db.users.find({ age: { $gte: 25 } }) |
|
$lt |
匹配字段值小于指定值的文档 | db.users.find({ age: { $lt: 25 } }) |
|
$lte |
匹配字段值小于等于指定值的文档 | db.users.find({ age: { $lte: 25 } }) |
|
$in |
匹配字段值在指定数组内的文档 | db.users.find({ role: { $in: ["admin", "editor"] } }) |
|
$nin |
匹配字段值不在指定数组内的文档 | db.users.find({ role: { $nin: ["guest", "viewer"] } }) |
|
$regex |
匹配字段值符合指定正则表达式的文档 | db.users.find({ name: { $regex: /^J/i } }) |
|
逻辑操作符 | $and |
逻辑与,匹配同时满足所有条件的文档 | db.users.find({ $and: [{ age: { $gt: 18 } }, { city: "Beijing" }] }) |
$or |
逻辑或,匹配满足至少一个条件的文档 | db.users.find({ $or: [{ age: { $lt: 18 } }, { age: { $gt: 65 } }] }) |
|
$not |
逻辑非,匹配不满足后续条件的文档 | db.users.find({ age: { $not: { $lt: 18 } } }) |
|
$nor |
逻辑或非,匹配所有条件都不满足的文档 | db.users.find({ $nor: [{ age: { $lt: 18 } }, { city: "Shanghai" }] }) |
|
元素操作符 | $exists |
匹配包含(true)或不包含(false)指定字段的文档 | db.users.find({ email: { $exists: true } }) |
$type |
匹配字段值为指定BSON数据类型的文档 | db.users.find({ age: { $type: "int" } }) |
|
数组操作符 | $all |
匹配数组字段包含所有指定元素的文档 | db.articles.find({ tags: { $all: ["mongodb", "database"] } }) |
$elemMatch |
匹配数组字段中至少有一个元素满足所有指定条件的文档 | db.scores.find({ results: { $elemMatch: { $gt: 80, $lt: 85 } } }) |
|
$size |
匹配数组长度等于指定值的文档 | db.users.find({ hobbies: { $size: 3 } }) |
|
其他操作符 | $text |
对建立了文本索引的字段执行文本搜索 | db.articles.find({ $text: { $search: "MongoDB tutorial" } }) |
$where |
使用JavaScript函数/表达式进行复杂条件过滤(性能需注意) | db.users.find({ $where: "this.age > this.balance / 1000" }) |
|
$near |
返回地理位置点接近指定点的文档(需地理空间索引) | db.places.find({ loc: { $near: [100, 20] } }) |
|
$geoWithin |
返回地理位置点在指定几何图形内的文档(需地理空间索引) | db.places.find({ loc: { $geoWithin: { $centerSphere: [[0, 0], 5] } } }) |
注意事项:
$where
和$regex
(尤其是左模糊匹配如/^abc/)可能导致查询性能下降,尤其是在大数据集上,使用时需谨慎。$text
和地理空间操作符则需要先创建相应的索引。- 查询数组:操作符
$all
和$elemMatch
都用于数组,但目的不同。$all
用于匹配数组包含特定元素,而$elemMatch
用于匹配数组中的元素满足某些条件。
更新操作符
类别 | 操作符 | 用途 | 简要示例(Shell环境) |
---|---|---|---|
字段更新 | $set |
设置字段的值。如果字段不存在,则创建它。 | { $set: { status: "Published", views: 0 } } |
$unset |
从文档中移除指定的字段。 | { $unset: { tempField: "" } } |
|
$inc |
将字段的值增加(或减少)指定的数值。 | { $inc: { stock: -1, score: 5 } } |
|
$rename |
重命名字段。 | { $rename: { oldName: "newName" } } |
|
$currentDate |
将字段的值设置为当前日期或时间戳。 | { $currentDate: { lastModified: true } } |
|
数组更新 | $push |
向数组末尾添加一个元素。 | { $push: { tags: "new" } } |
$addToSet |
向数组中添加一个元素,但仅当该元素不存在于数组中时才会添加(确保唯一性)。 | { $addToSet: { tags: "unique" } } |
|
$pop |
移除数组的第一个 (-1 ) 或最后一个 (1 ) 元素。 |
{ $pop: { scores: -1 } } (移除scores 数组的第一个元素) |
|
$pull |
从数组中移除所有匹配指定条件的元素。 | { $pull: { tags: { $in: ["obsolete", "old"] } } } |
|
其他 | $setOnInsert |
如果更新操作导致插入新文档(即使用upsert: true 时),则设置字段的值。 |
{ $setOnInsert: { createdAt: new Date() } } |