Mongodb初体验

90 阅读2分钟

Tips: 本篇记录的版本信息如下

mongodb-community@7.0.2

mongosh@2.1.1

简单了解

数据库(database) - 表(collections) - 字段和值(Document)

image.png

安装mongodb server社区版

  1. 安装(本示例是用brew安装的)
brew install mongodb-community
  1. 安装成功后会有提示如何开启服务
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

  1. 安装
brew install mongosh
  1. 进入mongo模式
mongosh
  1. 退出
  • Type .exitexit, or exit().
  • Type quit or quit().
  • Press Ctrl + D.
  • Press Ctrl + C twice.

小技巧:想要在终端中换行输入,可先输入一个左括号(,然后回车就换行了,效果如下:

image.png

mongosh使用

在使用mongosh之前,如果脑海中无法想象数据结构,可以配合使用mongodb可视化工具studio-3t目前(2024.1.3)可试用30天

安装命令

brew install studio-3t

image.png

官网API传送门: www.mongodb.com/docs/manual…

数据库Database

增 / 切换数据库

use命令,如果此数据库不存在,则新增,否则为切换

use testdb

image.png

Tip: 注意要先切换到要删除的数据库,此命令是要删除当前所在的数据库

db.dropDatabase()

image.png

此版本没有直接修改数据库名称的方法,若需要将数据库a中的集合转移到数据库b,可采用如下方案转移表的方式

db.adminCommand({
... renameCollection: "testdb.t1",
... to: "mydb.t1",
... })

上述指令是指将数据库testdb下的t1集合转移到mydb数据库并命名为t1

image.png

show dbs

image.png

集合Collections

# 插入一个空的集合
db.createCollection('t0')

image.png

# 新建集合t1并插入单条数据
db.t1.insertOne({ aaa: 1 })

image.png

db.t0.drop()

image.png

db.t1.renameCollection('t2')

image.png

show collections

image.png

字段和值Document

# 在集合t1中插入单条数据
db.t1.insertOne({ aaa: 1 })

image.png

# 在集合t2中插入多条数据
db.t2.insertMany(
... [
... { str: 'string1', num: 1 },
... { str: 'string2', num: 2 },
... { str: 'string3', num: 3 },
... ]
... )

image.png

# 删除一条
db.t1.deleteOne({ a: 1 })

# 删除多条
db.t1.deleteMany({ a: 1 })

image.png

# 修改单条
db.t1.updateOne({ a: 1 }, { $set: { a: 2, b: 3 } })

# 修改多条
db.t1.updateMany({ b: { $lt: 2 } }, { $set: { a: 1, b: 2 } })

image.png

db.t1.find()

image.png

用到哪看到哪,不定期更新......