DEV Community

Cover image for MongoDB giving user permission to view only single collection.
Minhaz
Minhaz

Posted on • Originally published at github.com

MongoDB giving user permission to view only single collection.

Purpose

Here I will install mongo and set it up in a way where an user can only read and write a single collection or multiple collection but not all.

As a result it will increase security of the db.

Steps

Install mongodb

docker run -dit --name mongo -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=mongoAdmin33 mongo
Enter fullscreen mode Exit fullscreen mode

Go into the docker container's mongosh

docker exec -it mongo bash -c "mongosh mongodb://admin:mongoAdmin33@localhost:27017/?authSource=admin"
Enter fullscreen mode Exit fullscreen mode

Use this command and see that all the dbs are visible

show dbs;
Enter fullscreen mode Exit fullscreen mode

It should show 3 collections like this -
Image description

Switch to a db using

use appleCollection;
Enter fullscreen mode Exit fullscreen mode

Image description

Insert some data

db.apples.insertMany([
    {
        title: "Green Apple"
    },
    {
        title: "Red Apple"
    },
    {
        title: "Black Apple"
    }
])
Enter fullscreen mode Exit fullscreen mode

after inserting data

Create an user and give him read write access for only this collection

db.createUser(
   {
     user: "apple_admin",
     pwd: "apple_admin_pass",
     roles: [ "readWrite", "dbAdmin" ]
   }
)
Enter fullscreen mode Exit fullscreen mode

It should say

after creating user

Exit from the current mongosh using

exit
Enter fullscreen mode Exit fullscreen mode

Login into mongosh using the new apple admin account

docker exec -it mongo bash -c "mongosh mongodb://apple_admin:apple_admin_pass@localhost:27017/?authSource=appleCollection"
Enter fullscreen mode Exit fullscreen mode

Please notice that we are using appleCollection as the auth source.

Now use the command to see dbs;

show dbs;
Enter fullscreen mode Exit fullscreen mode

Only one db should be visible.

Image description

Select data from this db.

db.apples.find({});
Enter fullscreen mode Exit fullscreen mode

find data

Switch to a different database

use randomDatabase;
Enter fullscreen mode Exit fullscreen mode

Query this database and it should show error.

show collections
Enter fullscreen mode Exit fullscreen mode

user don't have permission for this db

Reference

This was one of my projects that I tried out first here. Here you can also find how to give a user multiple database’s permission.
devops-notes/61. setup mongodb and give specific user permission to specific collection. I will update the github if I find something.

[Github]Giving user permission to specific database

Enjoy and let me know if any problem occurs.

Top comments (0)