Role for a db user who can also `enableSharding` and `shardCollection`

Hi everyone,

I have setup a shared cluster and now creating a user for a particular db with readWrite permission. What I also want this user can do is, he can create collections, enableSharding, shardCollection but can not delete the collection/db.

I could not find any Built-In-role for this exact purpose. I mean I can give root access to that user, but then he will have access to all the databases which I dont want.

I tried creating a user from admin db and credentials but failed. For example, my db is demo and collection is users

So I created role my-user-role with enableSharding and shardCollection actions which can only access demo db (not sure if this is correct) .

use admin 
db.createRole(
   {
     role: "my-user-role",
     privileges: [
       { resource: { cluster: true }, actions: [ "enableSharding", "shardCollection" ] }
     ],
     roles: [
       { role: "readWrite", db: "demo" }
     ]
   }
)

the role is created, next I want to create a new user (who only has access to demo db) and assign this role to that user:

use admin
db.createUser({
    user: 'demo-db-user',
    pwd: 'somepwd',
    roles: [
        {
            role: 'my-user-role', db: 'demo'
        }
    ]
})

But I get error like this:

MongoServerError: Could not find role: my-user-role@demo

I assume, I can not have a user with cluster permission on a db? What is the best way to achive this then?

Hi @VISHWAS_B_ANAND and welcome to MongoDB community forums!!

Lets begin with each of the permissions one by one:

  1. enableSharding: If you are on MongoDB version 6.0 and above, you do not need to add this role explicitly to shard the collection.
  2. 'shardCollection` This would also be allowed by default in all the version.
  3. To make the user not allowed to delete the collection, you need to add the right privileges on collections. The documentation on collection wide access control provides you with further details on the privileges needed.

You can use the command below to create the user:

db.createUser({
  user: "yourUsername",
  pwd: "yourPassword",
  roles: [
    {
      role: "readWrite",
      db: db: <DatabaseName>,
      collection: <CollectionName>,
      privileges: [
        { resource: { db: <DatabaseName>, collection: <CollectionName> }, actions: ["find", "update", "insert"] }
      ]
    },
    {
      role: "read",
      db: db: <DatabaseName>,
      collection: <CollectionName>,
      privileges: [
        { resource: { db: <DatabaseName>, collection: <CollectionName> }, actions: ["find"] }
      ]
    }
  ]
})

Please reach out in case you have any further questions.

Warm regards
Aasawari