Hi Yann,
You are on the right track in terms of creating a custom role having limited privileges. Following are example steps that I used to satisfy your access requirement:
1) Create a custom role and a user:
db.runCommand({ createRole: "appUserRole",
privileges: [
{ resource:
{ db: "myApp" , collection: "" }
,
actions: [ "find", "createCollection"] },
{ resource:
{ db: "myApp", collection: "logs" }
,
actions: [ "insert","find" ] },
{ resource:
{ db: "myApp", collection: "data" }
,
actions: [ "insert", "update", "remove", "compact" ] },
{ resource:
{ db: "myApp", collection: "js" }
,
actions: [ "find" ] },
],
roles: [],
})
db.createUser(
{
user: "appUser",
pwd: "appUser",
roles: [
{ role: "appUserRole", db: "admin" }
]
}
)
2) Restart mongod with --auth or keyfile parameter. For example:
mongod --dbpath "/data/db1" --auth
3) Connect mongo shell to database:
mongo -u appUser -p appUser --authenticationDatabase admin
Next, I ran following shell commands and as expected, I was disallowed from using stats command.
> use myApp
switched to db myApp
> db.logs.insert({})
WriteResult(
{ "nInserted" : 1 }
)
> db.logs.find()
{ "_id" : ObjectId("55cae15895aaaf3153e6515f") }
> db.logs.stats()
{
"ok" : 0,
"errmsg" : "not authorized on myApp to execute command
{ collStats: \"logs\", scale: undefined }
",
"code" : 13
}
The behaviour that you noticed indicates that perhaps, server was not running in the "Authentication" mode. Can you please try above steps and see if this resolves your issue?
Regards,
ankit