Skip to content

Connect to Percona Server for MongoDB

After you have successfully installed and started Percona Server for MongoDB, let’s connect to it.

By default, access control is disabled in MongoDB. We recommend enabling it so that users must verify their identity to be able to connect to the database. Percona Server for MongoDB supports several authentication methods. We will use the default one, SCRAM, to configure authentication.

The steps are the following:

  1. Connect to Percona Server for MongoDB instance without authentication:

    $ mongosh
    
    Sample output
    Current Mongosh Log ID: 6598270a3a0c418751550ded
    Connecting to:      mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.0.0
    Using MongoDB:      7.0.15-9
    Using Mongosh:      2.0.0    
    
    For mongosh info see: https://docs.mongodb.com/mongodb-shell/    
    
    test>
    
  2. Create the administrative user in the admin database:

    1. Switch to the admin database

      > use admin
      
      Sample output
      switched to db admin
      
    2. Create the user:

      > db.createUser(
          {
            user: "admin",
            pwd: passwordPrompt(), // or cleartext password
            roles: [
              { role: "userAdminAnyDatabase", db: "admin" },
              { role: "readWriteAnyDatabase", db: "admin" }
            ]
          }
        )
      
  3. Shutdown the mongod instance and exit mongosh

    > db.adminCommand( { shutdown: 1 } )
    
  4. Enable authentication

    Start the server with authentication enabled using the following command:

    $ mongod --auth --port 27017 --dbpath /var/lib/mongodb --fork --syslog
    
    1. Edit the configuration file

      /etc/mongod.conf
      security:
          authorization: enabled
      
    2. Start the mongod service

      $ systemctl start mongod
      
  5. Connect to Percona Server for MongoDB and authenticate.

    $ mongosh --port 27017  --authenticationDatabase \
    "admin" -u "admin" -p
    

Next steps

Run simple queries

Get expert help

If you need assistance, visit the community forum for comprehensive and free database knowledge, or contact our Percona Database Experts for professional support and services.