mongodb数据库应用

一、理论

mongodb是一个文档型数据库,数据以类似json的文档形式存储。

mongodb用于应对大数据量、高性能和灵活性需求。

mongodb使用集合(collections)来组织文档(documents),每个文档都是由键值对组成的。

mongodb专业术语

sql术语 mongodb术语/概念 解释/说明

database database 数据库

table collection 数据库表/集合

row document 数据记录行/文档

column field 数据字段/域

index index 索引

table joins 表连接,mongodb不支持

primary key primray key 主键,mongodb自动将_id字段设置为主键

数据结构

database

collection

document

库中可包含一个或多个collection(集合),集合是一组document(文档)的容器,一个集合中的文档不需要有一个固定的模式。

二、实践

bash 复制代码
[root@localhost ~]# dnf -y install libcurl openssl gcc make perl 
[root@localhost ~]# tar zxf mongodb-linux-x86_64-rhel8-8.0.8.tgz 
[root@localhost ~]# mv mongodb-linux-x86_64-rhel88-8.0.8 /usr/local/mongodb
[root@localhost ~]# echo 'export PATH=/usr/local/mongodb/bin:$PATH' >> /etc/profile  
[root@localhost ~]# source /etc/profile

mongodb默认数据存储目录 /var/lib/mongodb 日志文件目录 /var/log/mongodb
在这里,提前创建这俩目录并设置当前用户有读写权限。
[root@localhost ~]# mkdir -p /var/lib/mongo
[root@localhost ~]# mkdir -p /var/log/mongodb
[root@localhost ~]# chown `whoami` /var/lib/mongo
[root@localhost ~]# chown `whoami` /var/log/mongodb

安装mongodb依赖的openssl11
[root@localhost ~]# tar zxf openssl-1.1.1w.tar.gz 
[root@localhost ~]# cd openssl-1.1.1w
[root@localhost openssl-1.1.1w]# ./config --prefix=/opt/openssl11 --openssldir=/opt/openssl11/ssl
[root@localhost openssl-1.1.1w]# make -j$(nproc)
[root@localhost openssl-1.1.1w]# make install
[root@localhost ~]# echo 'export  LD_LIBRARY_PATH=/opt/openssl11/lib:$LB_LIBRARY_PATH' | tee /etc/profile.d/openssl11.sh
export  LD_LIBRARY_PATH=/opt/openssl11/lib:$LB_LIBRARY_PATH
[root@localhost ~]# source /etc/profile.d/openssl11.sh 

启动mongodb
[root@localhost ~]# mongod --dbpath /var/lib/mongo --logpath /var/log/mongodb/mongod.log --fork
about to fork child process, waiting until server is ready for connections.
forked process: 12576
child process started successfully, parent exiting

安装mongodb shell
[root@localhost ~]# tar zxf mongosh-2.5.0-linux-x64-openssl3.tgz 
[root@localhost ~]# cd mongosh-2.5.0-linux-x64-openssl3
[root@localhost mongosh-2.5.0-linux-x64-openssl3]# cd bin/
[root@localhost bin]# cp mongosh /usr/local/bin/
[root@localhost bin]# cp mongosh_crypt_v1.so /usr/local/lib/

启动mongodb shell
[root@localhost ~]# mongosh
Current Mongosh Log ID:	6805b5241958b5d28d1b26ff
Connecting to:		mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.5.0
Using MongoDB:		8.0.8
Using Mongosh:		2.5.0

For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/


To help improve our products, anonymous usage data is collected and sent to MongoDB periodically (https://www.mongodb.com/legal/privacy-policy).
You can opt-out by running the disableTelemetry() command.

------
   The server generated these startup warnings when booting
   2025-04-21T10:57:04.875+08:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
   2025-04-21T10:57:05.730+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
   2025-04-21T10:57:05.730+08:00: You are running this process as the root user, which is not recommended
   2025-04-21T10:57:05.730+08:00: This server is bound to localhost. Remote systems will be unable to connect to this server. Start the server with --bind_ip <address> to specify which IP addresses it should serve responses from, or with --bind_ip_all to bind to all interfaces. If this behavior is desired, start the server with --bind_ip 127.0.0.1 to disable this warning
   2025-04-21T10:57:05.730+08:00: Soft rlimits for open file descriptors too low
   2025-04-21T10:57:05.730+08:00: For customers running the current memory allocator, we suggest changing the contents of the following sysfsFile
   2025-04-21T10:57:05.730+08:00: We suggest setting the contents of sysfsFile to 0.
   2025-04-21T10:57:05.731+08:00: We suggest setting swappiness to 0 or 1, as swapping can cause performance problems.
------

test> 

查看数据库列表
	test> show dbs		
	admin   40.00 KiB
	config  60.00 KiB
	local   40.00 KiB

查看当前数据库
	test> db		
	test

创建数据库
	test> use runoob	
	switched to db runoob
	runoob> db
	runoob
	runoob> 

新创建的数据库不写数据,在数据库列表中看不到。
	runoob> show dbs
	admin   40.00 KiB
	config  60.00 KiB
	local   40.00 KiB

	runoob> db.runoob.insertOne({"name":"zhangsan"})
	
	{
 	  acknowledged: true,
	  insertedId: ObjectId('6805b5d21958b5d28d1b2700')
	}
	
	runoob> show dbs
	admin   40.00 KiB
	config  60.00 KiB
	local   40.00 KiB
	runoob  40.00 KiB

删除当前使用的数据库及其所有集合
	runoob> use myDatabase
	switched to db myDatabase
	myDatabase> db.dropDatabase() 

查看当前库已有集合
	runoob> show collections
	runoob
	runoob> show tables	
	runoob

创建一个集合的实例。
具有特性:
	固定大小,最大10MB,最多存储5000个文档。
	文档必须包含name和email字段,其中name必须是字符串,email必须是有效的电子邮件格式。
	验证级别为严格,验证失败将阻止插入或更新。
	使用WiredTiger存储引擎,指定块压缩器为zstd。
	默认使用英语排序规则。

runoob> db.createCollection("myComplexCollection",{
capped:true,
size:10485760,
max:5000,
validator:{ $jsonSchema: {
bsonType: "object",
required: ["name","email"],
properties: {
name: {
bsonType: "string",
description: "string"
},
email: {
bsonType: "string",
pattern: "^.+@.+$",
description: "string"
}
}
}},
validationLevel: "strict",
validationAction: "error",
storageEngine: {
wiredTiger: { configString: "block_compressor=zstd"}
},
collation: { locale: "en",strength:2}
});
{ ok: 1 }

在test数据库中创建runoob集合。
test> db.createCollection("runoob")
{ ok: 1 }

注意:在mongodb中,集合只有在内容插入后才会创建,就是说,创建集合(数据表)后要再插入一个文档(记录),集合才会真正创建。

更新集合名
	test> db.adminCommand({ renameCollection: "test.runoob",to: "test.aaa" });
	{ ok: 1 }

删除集合
	test> show collections
	aaa
	test> db.aaa.drop()
	true
	test> show collections

再次查看,发现已被删除。

在集合中插入单个文档
	test> db.myCollection.insertOne({
	... name: "Alice",
	... age: 25,
	... city: "New York"
	... });
	{
	  acknowledged: true,
	  insertedId: ObjectId('6805baf51958b5d28d1b2701')
	}

在集合中插入多个文档
	test> db.myCollection.insertMany([
	... {name:"Bob",age:30,city:"Los Angeles"},
	... {name:"Charlie",age:35,city:"Chicago"}]);
	{
	  acknowledged: true,
	  insertedIds: {
	    '0': ObjectId('6805bb781958b5d28d1b2702'),
	    '1': ObjectId('6805bb781958b5d28d1b2703')
	  }
	}


查找所有文档
test> db.myCollection.find();
[
  {
    _id: ObjectId('6805baf51958b5d28d1b2701'),
    name: 'Alice',
    age: 25,
    city: 'New York'
  },
  {
    _id: ObjectId('6805bb781958b5d28d1b2702'),
    name: 'Bob',
    age: 30,
    city: 'Los Angeles'
  },
  {
    _id: ObjectId('6805bb781958b5d28d1b2703'),
    name: 'Charlie',
    age: 35,
    city: 'Chicago'
  }
]

按条件查找文档
test> db.myCollection.find({age:{ $gt:25}});  $gt表示大于
[
  {
    _id: ObjectId('6805bb781958b5d28d1b2702'),
    name: 'Bob',
    age: 30,
    city: 'Los Angeles'
  },
  {
    _id: ObjectId('6805bb781958b5d28d1b2703'),
    name: 'Charlie',
    age: 35,
    city: 'Chicago'
  }
]

按条件查找文档,并只返回指定字段。
test> db.myCollection.find(
... { age: { $gt:25}},
... {name: 1,age:1,_id:0});
[ { name: 'Bob', age: 30 }, { name: 'Charlie', age: 35 } ]

注: { name: 1, age:1, _id:0 } -投影(Projection) 用于控制返回的字段(类似SQL中的select语句) :1表示包含该字段, 0表示排除该字段。 例如 _id:0 表示排除默认返回的 _id字段。所以最终返回的文档仅包含name和age字段。

查找单个文档
test> db.myCollection.findOne({name:"Alice"});
{
  _id: ObjectId('6805baf51958b5d28d1b2701'),
  name: 'Alice',
  age: 25,
  city: 'New York'
}

查找单个文档,并只返回指定字段。
test> db.myCollection.findOne(
... {name:"Alice"},
... {name:1,age:1,_id:0});
{ name: 'Alice', age: 25 }

删除匹配过滤器的单个文档
test> db.myCollection.deleteOne({name:"Alice"});
{ acknowledged: true, deletedCount: 1 }

删除所有匹配过滤器的文档。
test> db.myCollection.deleteMany({name:"Bob"});
{ acknowledged: true, deletedCount: 1 }

返回被删除的文档,如果找不到匹配的文档,则返回null。
test> db.myCollection.findOneAndDelete(
... {name:"Charlie"},
... {projection:{name:1,age:1}}
... );
{ _id: ObjectId('6805bb781958b5d28d1b2703'), name: 'Charlie', age: 35 }

插入测试数据
test> db.myCollection.insertMany([{name:"Alice",age:25,city:"Los Angeles",status:"inactive"},{name:"Bob",age:30,city:"Los Angeles",status:"active"},{name:"Charlie",age:35,city:"Chicago",status:"active"}]);
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId('6805bf3a1958b5d28d1b2704'),
    '1': ObjectId('6805bf3a1958b5d28d1b2705'),
    '2': ObjectId('6805bf3a1958b5d28d1b2706')
  }
}

更新单个文档
test> db.myCollection.updateOne(
... {name:"Alice"},
... {$set:{age:26}});
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

更新多个文档
test> db.myCollection.updateMany(
... {age:{$lt:30}},
... {$set:{status:"active"}});
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

替换单个文档
test> db.myCollection.replaceOne(
... {name:"Bob"},
... {name:"Bob",age:31});
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

查找并更新单个文档
test> db.myCollection.findOneAndUpdate(
... {name:"Charlie"},	过滤条件
... {$set:{age:36}},	更新操作
... {returnDocument:"after"});   可选参数,返回更新后的文档
{
  _id: ObjectId('6805bf3a1958b5d28d1b2706'),
  name: 'Charlie',
  age: 36,
  city: 'Chicago',
  status: 'active'
}

安装备份与恢复命令
[root@localhost ~]# rpm -ivh mongodb-database-tools-rhel70-x86_64-100.12.0.rpm 


[root@localhost ~]# mongodump # 执行此命令后,客户端会连接到ip为127.0.0.1 端口为27017的mongodb服务上,并备份所有数据到命令执行所在的目录下的dump/目录中。
2025-04-21T11:52:47.603+0800	writing admin.system.version to dump/admin/system.version.bson
2025-04-21T11:52:47.605+0800	done dumping admin.system.version (1 document)
2025-04-21T11:52:47.607+0800	writing test.myCollection to dump/test/myCollection.bson
2025-04-21T11:52:47.608+0800	writing runoob.myComplexCollection to dump/runoob/myComplexCollection.bson
2025-04-21T11:52:47.719+0800	done dumping test.myCollection (3 documents)
2025-04-21T11:52:47.720+0800	done dumping runoob.myComplexCollection (0 documents)
2025-04-21T11:52:47.722+0800	writing runoob.runoob to dump/runoob/runoob.bson
2025-04-21T11:52:47.723+0800	done dumping runoob.runoob (1 document)

[root@localhost ~]# ls
anaconda-ks.cfg
dump
[root@localhost ~]# cd dump
[root@localhost dump]# ls
admin  prelude.json  runoob  test

执行此命令恢复数据,会从当前执行命令的路径下的dump目录中读取备份数据。
[root@localhost ~]# mongorestore
2025-04-21T11:54:56.322+0800	using default 'dump' directory
2025-04-21T11:54:56.322+0800	preparing collections to restore from
2025-04-21T11:54:56.322+0800	don't know what to do with file "dump/prelude.json", skipping...
2025-04-21T11:54:56.322+0800	reading metadata for runoob.myComplexCollection from dump/runoob/myComplexCollection.metadata.json
2025-04-21T11:54:56.323+0800	reading metadata for runoob.runoob from dump/runoob/runoob.metadata.json
2025-04-21T11:54:56.323+0800	reading metadata for test.myCollection from dump/test/myCollection.metadata.json
2025-04-21T11:54:56.325+0800	restoring to existing collection test.myCollection without dropping
2025-04-21T11:54:56.325+0800	restoring test.myCollection from dump/test/myCollection.bson
2025-04-21T11:54:56.327+0800	restoring to existing collection runoob.runoob without dropping
2025-04-21T11:54:56.327+0800	restoring runoob.runoob from dump/runoob/runoob.bson
2025-04-21T11:54:56.381+0800	restoring to existing collection runoob.myComplexCollection without dropping
2025-04-21T11:54:56.381+0800	restoring runoob.myComplexCollection from dump/runoob/myComplexCollection.bson
2025-04-21T11:54:56.388+0800	continuing through error: E11000 duplicate key error collection: runoob.runoob index: _id_ dup key: { _id: ObjectId('6805b5d21958b5d28d1b2700') }
2025-04-21T11:54:56.406+0800	continuing through error: E11000 duplicate key error collection: test.myCollection index: _id_ dup key: { _id: ObjectId('6805bf3a1958b5d28d1b2704') }
2025-04-21T11:54:56.406+0800	continuing through error: E11000 duplicate key error collection: test.myCollection index: _id_ dup key: { _id: ObjectId('6805bf3a1958b5d28d1b2705') }
2025-04-21T11:54:56.406+0800	continuing through error: E11000 duplicate key error collection: test.myCollection index: _id_ dup key: { _id: ObjectId('6805bf3a1958b5d28d1b2706') }
2025-04-21T11:54:56.406+0800	finished restoring test.myCollection (0 documents, 3 failures)
2025-04-21T11:54:56.406+0800	finished restoring runoob.myComplexCollection (0 documents, 0 failures)
2025-04-21T11:54:56.406+0800	finished restoring runoob.runoob (0 documents, 1 failure)
2025-04-21T11:54:56.406+0800	no indexes to restore for collection runoob.myComplexCollection
2025-04-21T11:54:56.406+0800	no indexes to restore for collection runoob.runoob
2025-04-21T11:54:56.406+0800	no indexes to restore for collection test.myCollection
2025-04-21T11:54:56.406+0800	0 document(s) restored successfully. 4 document(s) failed to restore.

创建用户并分配readWrite和dbAdmin角色
test> db.createUser({
... user:"testuser",
... pwd:"password123",
... roles:[
... {role:"readWrite",db:"<test>"},
... {role:"dbAdmin",db:"<test>"}
... ]})
{ ok: 1 }
验证用户
test> db.auth("testuser","password123")
{ ok: 1 }

vim /usr/local/mongodb/mongod.conf


mongod -f /usr/local/mongodb/mongod.conf

or

mongod --auth --dbpath /var/log/mongo --logpath /var/log/mongodb/mongod.log -fork

[root@bogon mongo]# mongod --auth --dbpath /var/lib/mongo --logpath /var/log/mongodb/mongodb.log --fork
about to fork child process, waiting until server is ready for connections.
forked process: 2484
child process started successfully, parent exiting

没有该文件,需要手动创建
[root@bogon mongo]# vim /usr/local/mongodb/mongod.conf
security:
        authorization:"enabled"


[root@bogon mongo]# mongosh
test> use testdb
switched to db testdb
testdb> db.createUser({
... user: "testuser",
... pwd: "password123",
... roles:[{ role: "readWrite",db: "testdb" },{ role: "read", db: "testdb"
... }]})
{ ok: 1 }


[root@bogon mongo]# mongosh --host localhost --port 27017 -u "testuser" -p "password123" --authenticationDatabase "testdb"
Current Mongosh Log ID:	6847a2982a6fba6bcd1b26ff
Connecting to:		mongodb://<credentials>@localhost:27017/?directConnection=true&serverSelectionTimeoutMS=2000&authSource=testdb&appName=mongosh+2.5.0
Using MongoDB:		8.0.8
Using Mongosh:		2.5.0
mongosh 2.5.2 is available for download: https://www.mongodb.com/try/download/shell

For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/

test> use testdb;
switched to db testdb
testdb> show collections;

testdb> exit


以上方式验证成功

还可以将配置文件写全一些
[root@bogon mongo]# vim /usr/local/mongodb/mongod.conf
# 系统日志配置
systemLog:
  destination: file
  path: /var/log/mongodb/mongod.log
  logAppend: true
  timeStampFormat: iso8601-utc

# 存储配置
storage:
  dbPath: /var/lib/mongo
  # journal选项在8.0+版本已移除,journaling总是启用

# 进程管理
processManagement:
  fork: true
  pidFilePath: /tmp/mongod.pid

# 网络配置
net:
  bindIp: 127.0.0.1
  port: 27017

# 安全配置
security:
  authorization: enabled

然后用mongod -f /usr/local/mongodb/mongod.conf 指定配置文件来启动。
[root@bogon mongo]# pkill mongo
[root@bogon mongo]# mongod -f /usr/local/mongodb/mongod.conf 
about to fork child process, waiting until server is ready for connections.
forked process: 2604
child process started successfully, parent exiting
[root@bogon mongo]# mongosh --host localhost --port 27017 -u "testuser" -p "password123" --authenticationDatabase "testdb"
Current Mongosh Log ID:	6847ab314825ef18a31b26ff
Connecting to:		mongodb://<credentials>@localhost:27017/?directConnection=true&serverSelectionTimeoutMS=2000&authSource=testdb&appName=mongosh+2.5.0
Using MongoDB:		8.0.8
Using Mongosh:		2.5.0
mongosh 2.5.2 is available for download: https://www.mongodb.com/try/download/shell

For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/

test> use testdb
switched to db testdb
testdb> show collections;

testdb> 
相关推荐
码出财富34 分钟前
SQL语法大全指南
数据库·mysql·oracle
异世界贤狼转生码农2 小时前
MongoDB Windows 系统实战手册:从配置到数据处理入门
数据库·mongodb
QuZhengRong3 小时前
【数据库】Navicat 导入 Excel 数据乱码问题的解决方法
android·数据库·excel
码农阿豪3 小时前
Windows从零到一安装KingbaseES数据库及使用ksql工具连接全指南
数据库·windows
时序数据说8 小时前
时序数据库市场前景分析
大数据·数据库·物联网·开源·时序数据库
听雪楼主.12 小时前
Oracle Undo Tablespace 使用率暴涨案例分析
数据库·oracle·架构
我科绝伦(Huanhuan Zhou)12 小时前
KINGBASE集群日常维护管理命令总结
数据库·database
妖灵翎幺12 小时前
Java应届生求职八股(2)---Mysql篇
数据库·mysql
HMBBLOVEPDX12 小时前
MySQL的事务日志:
数据库·mysql
weixin_4196583114 小时前
MySQL数据库备份与恢复
数据库·mysql