0
0
MongoDBquery~30 mins

Role-based access control in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Role-based Access Control with MongoDB
📖 Scenario: You are building a simple user management system for a small company. The system needs to control what actions users can perform based on their roles.For example, an admin can read and write all data, a manager can read and write some data, and a viewer can only read data.
🎯 Goal: Create a MongoDB collection to store users with their roles and permissions. Then, define a query to find users who have permission to write data.
📋 What You'll Learn
Create a MongoDB collection named users with documents containing username, role, and permissions fields.
Define roles with specific permissions: admin has read and write, manager has read and write, viewer has only read.
Write a query to find all users who have write permission.
💡 Why This Matters
🌍 Real World
Role-based access control is used in many applications to restrict what users can do based on their roles, improving security and organization.
💼 Career
Understanding how to manage user roles and permissions in databases is essential for backend developers, database administrators, and security engineers.
Progress0 / 4 steps
1
Create the users collection with user documents
Create a MongoDB collection called users and insert these exact documents: { username: "alice", role: "admin", permissions: ["read", "write"] }, { username: "bob", role: "manager", permissions: ["read", "write"] }, and { username: "carol", role: "viewer", permissions: ["read"] }.
MongoDB
Need a hint?

Use db.users.insertMany() with an array of user objects.

2
Define a variable for the write permission
Create a variable called writePermission and set it to the string "write" to represent the write permission.
MongoDB
Need a hint?

Use const writePermission = "write" to create the variable.

3
Write a query to find users with write permission
Write a MongoDB query called usersWithWrite that finds all documents in the users collection where the permissions array contains the value stored in writePermission.
MongoDB
Need a hint?

Use db.users.find({ permissions: writePermission }) to find users with write permission.

4
Complete by adding a projection to show only usernames
Modify the usersWithWrite query to include a projection that returns only the username field and excludes the _id field.
MongoDB
Need a hint?

Use the projection option in find() to select fields.