Search code examples
mongodbuser-rolesmongodb-roles

MongoDB How to create a User with ReadWriteAnyDatabase role but exclude the admin database


I'm trying to create an extended role that allows - read/write on any database - allow collMod on any database - allow createCollection on any database - readonly on admin database

I tried the following

use admin
db.runCommand({ createRole: "_ReadWriteAnyDatabase",
  privileges: [
    { resource: { db: "", collection: "" }, actions: [ "collMod", "createCollection" ] }
  ],
  roles: [
    "readWriteAnyDatabase",
    { role: "read", db : "admin" }
  ]
})

then I created the user on the admin database, because I wasn't able to create the user on an alternative database

but i found out that I can create and delete collections on the admin database

mongo admin -u user1 -p user1
db.createCollection('mycollection')
{ ok : 1 }
db.mycollection.drop()
{ ok : 1 }

Solution

  • If you give user "readWriteAnyDatabase" role, you cannot exclude admin DB. So, solution is give use "readWrite" role to all other databases, but then that users cannot create new databases.

    You can create script (loop; forEach()) what lists all databases (excluding admin, local, config) and grant "readWrite" right to user.