二|mongoDB常见终端操作指令

55 阅读2分钟

前情提要:以下所有指令都需要运行在终端2mongo,不知道终端2点击以下链接:

安装与启动: 一|macOS环境安装mongoDB

1.数据库操作

显示数据库

show dbs

// admin 0.000GB 
// config 0.000GB 
// local 0.000GB

切换数据库(如果不存在就自动创建数据库,如果是空会不显示。)

use test 
// switched to db test ,此时数据库为空,需要为test数据库创建一个集合

db.createCollection('name')
// 创建一个集合  { "ok" : 1 }

show dbs
// 再次查看 
// admin 0.000GB config 0.000GB local 0.000GB test 0.000GB

查看当前所在数据库

db

删除当前所在数据库

db.dropDatabase()
//  { "ok" : 1 }

2.集合操作

创建一个集合

db.createCollection('age') 
// { "ok" : 1 }

显示所有集合

show collections

删除指定的xxx集合

db.xxx.drop()

重命名指定的xxx为xxx2集合

db.xxx.renameCollection('xxx2') 
// { "ok" : 1 }

3.文档操作

在指定的xxx2的集合中插入文档

db.xxx.insert({name:'李美美',age:18}) 
// WriteResult({ "nInserted" : 1 })

查看指定集合中的文档

> db.xxx2.find() 
// { "_id" : ObjectId("65007c00a6c7f43f711462fe"), "name" : "李美美", "age" : 18 } >

查看指定集合中的文档(配置搜索条件,如年龄必须为18)

> db.xxx2.find({age:18})
// { "_id" : ObjectId("65007c00a6c7f43f711462fe"), "name" : "李美美", "age" : 18 } >

修改指定集合中的文档(如修改年龄为30)

db.xxx2.update({name:'李美美'},{age:30}) 
// WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) 

db.xxx2.find()  
// { "_id" : ObjectId("65007c00a6c7f43f711462fe"), "age" : 30 }

如果是部分修改指定集合中的文档(如修改年龄为30)

db.name2.update({name:'李美美'},{$set:{age:30}})

db.name2.find() 
// { "_id" : ObjectId("65007dbfa6c7f43f711462ff"), "name" : "李美美", "age" : 30 }

删除指定集合中的文档

db.name2.remove({name:'王小明'}) 
// WriteResult({ "nRemoved" : 1 })