Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

330
Views
Create user only if not exists in MongoDB (simple example)

I'm newby to MongoDB and .js.

I have a simple add_app_user.js script with the following content:

# MongoDB shell version v4.2.17
# Set the database to 'testdb'.
db = db.getSiblingDB('testdb');

# Create new user.
db.createUser(
   {
     user: "testuser",
     pwd: "testpass",
     roles: [ "readWrite" ]
   }
);

This works fine for the first time (when such a user doesn't exist).

I need to make it idempotent.

I couldn't find an simple to understand script that will check for the "testuser" availability in the "testdb" and run my script block only if the check fails.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Try this:

if (db.getUser("testuser") == null) {  
   db.createUser(
     {
     user: "testuser",
     pwd: "testpass",
     roles: [ "readWrite" ]
     }
   );
}

NB, usually users are created in admin database. Actually I don't know any reason why they should be created anywhere else.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!