In mongo shell, I ran the following commands:

use mydatabase
db.createUser( { user: "john", pwd: "mongopass", roles: [ "readWrite", "dbAdmin" ] });

Mongo reported a success response. So then from terminal, I typed mongo --username john --password, and when prompted for password, I typed mongopass. But the result I got was:

connecting to: mongodb://
Error: Authentication failed. :
exception: connect failed
exiting with code 1

How do I login to mongodb with a username and password?

This is my /etc/mongo.conf

# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# where to write logging data.
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# Where and how to store data.
  dbPath: /var/lib/mongo
    enabled: true
#  engine:
#  wiredTiger:

# how the process runs
  fork: true  # fork and run in background
  pidFilePath: /var/run/mongodb/mongod.pid  # location of pidfile
  timeZoneInfo: /usr/share/zoneinfo

# network interfaces
  port: 27017





## Enterprise-Only Options


  • Can you add your mongo.conf file, there is a option for auth enable. Did you enable that? – Yunus UYANIK Oct 26 '20 at 20:40
  • OK i just added my /etc/mongo.conf – John Oct 26 '20 at 20:42
  • Typically users are created in internal database admin rather than mydatabase or any other custom DB. Honestly I don't know any use case where it would make sense to create users in any other database than admin. Maybe if you run a giant MongoDB which hosts a bunch of fully independent applications. – Wernfried Domscheit Oct 27 '20 at 10:04

MongoDB auth setting is false as a default.

First of all, you should create the root user.

//create new user with the root role (also, named root):
use admin
  user: "root",
  pwd: "pass",
  roles : [ "root" ]

After that, you should start your mongod service with the auth option, it means authentication is enabled.

mongod --auth

Also, you can add your mongod.conf file this parameter :

    authorization: enabled

And start your mongod with the command which is below.

mongod --config /etc/mongod.conf //your mongod.conf path

Check this out for more info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.