mongodb add user
This tutorial introduces some operations of adding users in mongodb
What are the users in mongodb
In mongodb, users are used to manage the permissions of each database. In order to control the permissions of the database, users need to be added, assigned permissions to the specified users, and specific users need to do specific operations.
What's the use of adding users
Subdivide permissions, restrict database access and use, and improve the security of mongodb.
Why add users
Prevent being used illegally, do some illegal operations, leading to some serious consequences.
For example, delete the library and run - = ≡∑ (((つ̀̀̀̀́́) つ
How to add users
First of all, verification will not be started when mongod is started
mongod
After mongod is started, connect to mongod
root@e444205572bd:/# mongo MongoDB shell version v4.1.9 connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID("e3fd959c-db96-4853-a306-9edcc8c5baa7") } MongoDB server version: 4.1.9 ......
Specify to admin database
> use admin switched to db admin
Create user with specified function
> db.createUser({user:"user", pwd:"123123", roles:["root"]}) Successfully added user: { "user" : "user", "roles" : [ "root" ] }
Users who view the database through show
> show users { "_id" : "admin.user", "userId" : UUID("95e02aca-49c2-4852-b2bc-7dc4f2738175"), "user" : "user", "db" : "admin", "roles" : [ { "role" : "root", "db" : "admin" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] }
User created successfully
How to connect mongodb after adding users
Connect with mongo
root@1410aa527d51:/# mongo -u user -p 123123 MongoDB shell version v4.1.9 connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID("8e9a9173-8263-40ea-b814-39090f0c90b7") } MongoDB server version: 4.1.9 ........
Connect in mgo
"mongodb://user:123123@localhost:27017"
info := &mgo.DialInfo{ Addrs:[]string{ "localhost:27017", }, Direct:false, Timeout:30 * time.Second, Database: "user", Source:"admin", Username:"user", Password:"123123", } session, err := mgo.DialWithInfo(info) //session, err := mgo.Dial(url) if err != nil { logs.Error(err) }
Note:
Through mongo deployed by docker, users can be created by adding the parameters mongo ﹣ initdb ﹣ root ﹣ username and mongo ﹣ initdb ﹣ root ﹣ password at startup. But if mongo didn't create users before, and you mount volume to map the db data in the container to the host, you need to manually create users in the container.