Tips: 本篇记录的版本信息如下
mongodb-community@7.0.2
mongosh@2.1.1
简单了解
数据库(database) - 表(collections) - 字段和值(Document)
安装mongodb server社区版
- 安装(本示例是用brew安装的)
brew install mongodb-community
- 安装成功后会有提示如何开启服务
brew services start mongodb/brew/mongodb-community
验证是否启动成功,网页输入地址:localhost:27017显示如下信息:
It looks like you are trying to access MongoDB over HTTP on the native driver port.
安装终端工具mongosh
- 安装
brew install mongosh
- 进入mongo模式
mongosh
- 退出
- Type
.exit,exit, orexit(). - Type
quitorquit(). - Press
Ctrl+D. - Press
Ctrl+Ctwice.
小技巧:想要在终端中换行输入,可先输入一个左括号
(,然后回车就换行了,效果如下:
mongosh使用
在使用mongosh之前,如果脑海中无法想象数据结构,可以配合使用mongodb可视化工具studio-3t目前(2024.1.3)可试用30天
安装命令
brew install studio-3t
官网API传送门: www.mongodb.com/docs/manual…
数据库Database
增 / 切换数据库
use命令,如果此数据库不存在,则新增,否则为切换
use testdb
删
Tip: 注意要先切换到要删除的数据库,此命令是要删除当前所在的数据库
db.dropDatabase()
改
此版本没有直接修改数据库名称的方法,若需要将数据库a中的集合转移到数据库b,可采用如下方案转移表的方式
db.adminCommand({
... renameCollection: "testdb.t1",
... to: "mydb.t1",
... })
上述指令是指将数据库testdb下的t1集合转移到mydb数据库并命名为t1
查
show dbs
集合Collections
增
# 插入一个空的集合
db.createCollection('t0')
# 新建集合t1并插入单条数据
db.t1.insertOne({ aaa: 1 })
删
db.t0.drop()
改
db.t1.renameCollection('t2')
查
show collections
字段和值Document
增
# 在集合t1中插入单条数据
db.t1.insertOne({ aaa: 1 })
# 在集合t2中插入多条数据
db.t2.insertMany(
... [
... { str: 'string1', num: 1 },
... { str: 'string2', num: 2 },
... { str: 'string3', num: 3 },
... ]
... )
删
# 删除一条
db.t1.deleteOne({ a: 1 })
# 删除多条
db.t1.deleteMany({ a: 1 })
改
# 修改单条
db.t1.updateOne({ a: 1 }, { $set: { a: 2, b: 3 } })
# 修改多条
db.t1.updateMany({ b: { $lt: 2 } }, { $set: { a: 1, b: 2 } })
查
db.t1.find()
用到哪看到哪,不定期更新......