Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB query to fetch only the "Name" field based on roles?
To fetch only the "Name" field based on specific roles in MongoDB, use the aggregation framework with $group, $setIsSubset, and $match operators. This approach filters documents by comparing their roles against a target role set.
Syntax
db.collection.aggregate([
{ $group: { _id: "$Name", "types": { $addToSet: "$Type" } } },
{ $project: { _id: 1, "types": 1, "isSubset": { $setIsSubset: [["TargetRole"], "$types"] } } },
{ $match: { "isSubset": false } },
{ $group: { _id: "$isSubset", "Name": { $push: "$_id" } } },
{ $project: { "_id": 0, "Name": 1 } },
{ $unwind: "$Name" }
]);
Sample Data
db.demo532.insertMany([
{ "Name": "Chris", "Type": "Admin" },
{ "Name": "David", "Type": "Guest" },
{ "Name": "Bob", "Type": "User" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e8b4a9def4dcbee04fbbbf9"),
ObjectId("5e8b4aa3ef4dcbee04fbbbfa"),
ObjectId("5e8b4ab0ef4dcbee04fbbbfb")
]
}
Display all documents ?
db.demo532.find();
{ "_id": ObjectId("5e8b4a9def4dcbee04fbbbf9"), "Name": "Chris", "Type": "Admin" }
{ "_id": ObjectId("5e8b4aa3ef4dcbee04fbbbfa"), "Name": "David", "Type": "Guest" }
{ "_id": ObjectId("5e8b4ab0ef4dcbee04fbbbfb"), "Name": "Bob", "Type": "User" }
Example: Fetch Names Excluding Admin Role
Get names of users who do NOT have "Admin" role ?
db.demo532.aggregate([
{ $group: { _id: "$Name", "types": { $addToSet: "$Type" } } },
{ $project: { _id: 1, "types": 1, "isSubset": { $setIsSubset: [["Admin"], "$types"] } } },
{ $match: { "isSubset": false } },
{ $group: { _id: "$isSubset", "Name": { $push: "$_id" } } },
{ $project: { "_id": 0, "Name": 1 } },
{ $unwind: "$Name" }
]);
{ "Name": "David" }
{ "Name": "Bob" }
How It Works
-
$groupgroups documents by Name and creates a types array -
$setIsSubsetchecks if ["Admin"] is a subset of each user's types -
$matchfilters users where isSubset is false (non-Admin users) -
$unwindflattens the Name array to individual documents
Conclusion
The aggregation pipeline with $setIsSubset efficiently filters documents by role comparison. This method returns only the Name field for users who don't match the specified role criteria.
Advertisements
