Install mongodb on Ubuntu 16.04, open permissions, create users, and log in users.


I once studied mongodb on, copied the code written by the teacher, and found that I could not log in the database with the user account and password in any case, so I spent a lot of time checking the official API. The conclusion is as follows.

1. Start mongod service first

> mongod –port 27017 –dbpath /data/db1

2. Connect to database

> mongo –port 27017

3. Create user

> use admin
> db.createUser( { user: “admin”, pwd: “123”, roles: [ { role: “userAdminAnyDatabase”, db: “admin” } ] })

4. Close mongod service

> use admin
> db.shutdownServer()

5. Restart the mongod service and add — auth to enable permission authentication.

> mongod –port 27017 –dbpath /data/db1 –auth

–At this time, we have two ways for users to log in to the database

6.1 mode 1: user authentication while connecting to the server

> mongo –port 27017 -u “admin” -p “123” –authenticationDatabase “admin”

6.2 mode 2: connect to the server first, and then authenticate in the database.

> mongo –port 27017
> use admin
> db.auth(“admin”,”123″)