# mongodb 的容器名称 mongo 进入 mongoDB 的 shell 工具$ docker exec -it mongotest_mongo_1 mongo# 然后进入管理员> use adminswitched to db admin# 输入配置中的账户密码> db.auth('root', 'example')1# 查看数据库> show dbsadmin 0.000GBconfig 0.000GBlocal 0.000GB# 创建一个新的数据库> use testdbswitched to db testdb# 创建一个新用户# 用户名是 test,密码是 123456,角色是数据库拥有者,拥有的数据库是testdb> db.createUser({user:'test',pwd:'123456',roles:[{role:'dbOwner', db:'testdb'}]})Successfully added user: {"user" : "test","roles" : [{"role" : "dbOwner","db" : "testdb"}]}
角色相关官方说明 https://docs.mongodb.com/manual/reference/built-in-roles/index.html
然后我们重新登录一次
$ docker exec -it mongomacos_mongo_1 mongo> use testdbswitched to db testdb> db.auth('test', '123456')1# 插入数据> db.users.insertOne({name:'zws',age:'25',email:'zws@qq.com'}){"acknowledged" : true,# 默认的ID值"insertedId" : ObjectId("603b3932b3ec63337b0050b4")}# 这里自动创建了名为users的集合,这个 collections 类似于MySQL的表> show collectionsusers# 查询数据db.users.find({}){ "_id" : ObjectId("5fafbfcfe8b2cc357c14a8de"), "name" : "zwx", "age" : "25", "email" : "work@zwx.ink" }# 再插入一条模式不一样的数据db.users.insertOne({name:'typ', age:26}){"acknowledged" : true,"insertedId" : ObjectId("5fafc132e8b2cc357c14a8df")}# 再次查询数据{ "_id" : ObjectId("5fafbfcfe8b2cc357c14a8de"), "name" : "zwx", "age" : "25", "email" : "work@zwx.ink" }{ "_id" : ObjectId("5fafc132e8b2cc357c14a8df"), "name" : "typ", "age" : 26 }# 更新数据 (查询条件,要更新的键值)> db.users.updateOne({name:'typ'},{$set:{email:'test@test.com'}}){ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }# 查询看是否更新成功db.users.find({name:'typ'}){ "_id" : ObjectId("5fafc132e8b2cc357c14a8df"), "name" : "typ", "age" : 26, "email" : "test@test.com" }
增删改查官方文档说明 https://docs.mongodb.com/manual/crud/
