How to set up authentication in MongoDB?
Oct 16, 2025 am 10:45 AMFirst enable authentication in the MongoDB configuration and then create users with roles to ensure secure access. Specific steps include: modify mongod.conf to enable authorization and restart the service; create an administrator user with the root role in the admin database; authenticate through db.auth or connection string; you can also create a user with limited permissions for a specific database, such as the readWrite user of myapp. This process ensures the safety of the production environment.
To set up authentication in MongoDB, you need to enable access control and create users with appropriate roles. This ensures that only authorized users can access your database. Here's how to do it step by step.
1. Enable Authentication in MongoDB Configuration
Before setting up users, you must configure MongoDB to require authentication.
- Open the MongoDB configuration file (usually mongod.conf , located at /etc/mongod.conf on Linux or C:\Program Files\MongoDB\Server\xx\bin\mongod.conf on Windows). - Under the security section, enable authorization: security:
authorization: enabled
sudo systemctl restart mongod (Linux)
or
Restart the MongoDB service via Services (Windows)
2. Create an Admin User
After enabling authorization, start the MongoDB shell and create a user with administrative privileges.
- Connect to MongoDB without authentication first:mongo
- Switch to the admin database:useadmin
- Create an admin user with the userAdminAnyDatabase role (or root for full access): db.createUser({
user: "adminUser",
pwd: "securePassword123",
roles: ["root"]
})
3. Authenticate When Connecting
Once authentication is enabled, users must log in to access the database.
- To authenticate in the MongoDB shell: useadmin
db.auth("adminUser", "securePassword123")
mongo -u adminUser -p securePassword123 --authenticationDatabase admin
For applications, include credentials in the connection string:mongodb://adminUser:securePassword123@localhost:27017/admin
4. Create Database-Specific Users
You can create users with limited access to specific databases.
- For example, to create a user for a database called myapp : use myapp
db.createUser({
user: "myappUser",
pwd: "appPass987",
roles: ["readWrite"]
})
Basically, just enable authorization in config, create a strong admin user, and use proper credentials when connecting. It's not complex but essential for production security.
The above is the detailed content of How to set up authentication in MongoDB?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

WiredTigerisMongoDB’sdefaultstorageenginesinceversion3.2,providinghighperformance,scalability,andmodernfeatures.1.Itusesdocument-levellockingandMVCCforhighconcurrency,allowingreadsandwritestoproceedwithoutblockingeachother.2.DataisstoredusingB-trees,

Select logging method: In the early stage, you can use the built-in error_log() for PHP. After the project is expanded, be sure to switch to mature libraries such as Monolog, support multiple handlers and log levels, and ensure that the log contains timestamps, levels, file line numbers and error details; 2. Design storage structure: A small amount of logs can be stored in files, and if there is a large number of logs, select a database if there is a large number of analysis. Use MySQL/PostgreSQL to structured data. Elasticsearch Kibana is recommended for semi-structured/unstructured. At the same time, it is formulated for backup and regular cleaning strategies; 3. Development and analysis interface: It should have search, filtering, aggregation, and visualization functions. It can be directly integrated into Kibana, or use the PHP framework chart library to develop self-development, focusing on the simplicity and ease of interface.

MongoDBintroducedmulti-documenttransactionsinversion4.0,enablingatomicoperationsacrosscollectionsforstrongconsistency.Transactionsallowmultipleread/writeoperationstobegroupedasasingleunit,eitherallsucceedingorfailingtogether.Theyaresupportedinreplica

Useproperindexesonquery,sort,andprojectionfields,favoringcompoundindexeswithequalitybeforerangefields,andavoidover-indexing;2.Optimizequeriesbyprojectingonlyneededfields,avoidingindex-blockingoperatorslike$whereandleading-wildcard$regex,andlimiting$i

DownloadMongoDBCommunityEditionfromtheofficialwebsite,selectingtheWindowsx64MSIpackage.2.RunthedownloadedMSIinstaller,chooseCompleteSetup,installMongoDBasaservice,andoptionallyskipMongoDBCompass.3.CreatethedatadirectorybymakingaC:\data\dbfolderusingF

InstallHomebrewifnotalreadyinstalled,thenrunbrewtapmongodb/brewandbrewinstallmongodb-communitytoinstallMongoDB.2.Starttheservicewithbrewservicesstartmongodb-community,whichrunsmongodinthebackgroundandenablesauto-startonboot.3.ConnectusingtheMongoDBsh

Transformdatamodelsbyembeddingorreferencingbasedonaccesspatternsinsteadofusingjoins;2.Handletransactionsbyfavoringatomicoperationsandeventualconsistency,reservingmulti-documenttransactionsforcriticalcases;3.RewriteSQLqueriesusingaggregationpipelinesa

Use Node.js, Socket.IO and MongoDB to build chat applications. First, build a technology stack and design a data model for users and messages. Use Mongoose to define schema and create indexes to improve query efficiency. Then, through Socket.IO, users join the room, send and receive messages in real time and load historical messages. After receiving the message, the server deposits it into MongoDB and pushes it to other members in the room. In order to support message history and expansion, use MongoDB query to sort messages by time to obtain messages, and load more content in combination with paging or infinite scrolling. It is recommended that MongoDBAtlas cloud service achieve automatic expansion and backup, and set TTL index to automatically clean up expired messages when necessary.
