- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB query to fetch only the “Name” field based on roles?
For this, use aggregate(). Here, we have considered 3 roles − Admin, Guest, and User. Let us create a collection with documents −
> db.demo532.insertOne({"Name":"Chris","Type":"Admin"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b4a9def4dcbee04fbbbf9") } > db.demo532.insertOne({"Name":"David","Type":"Guest"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b4aa3ef4dcbee04fbbbfa") } > db.demo532.insertOne({"Name":"Bob","Type":"User"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b4ab0ef4dcbee04fbbbfb") }
Display all documents from a collection with the help of find() method −
> db.demo532.find();
This will produce the following output −
{ "_id" : ObjectId("5e8b4a9def4dcbee04fbbbf9"), "Name" : "Chris", "Type" : "Admin" } { "_id" : ObjectId("5e8b4aa3ef4dcbee04fbbbfa"), "Name" : "David", "Type" : "Guest" } { "_id" : ObjectId("5e8b4ab0ef4dcbee04fbbbfb"), "Name" : "Bob", "Type" : "User" }
Following is the query to get a unique document which needs to be compared with other documents in the same collection −
> 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"} ... ])
This will produce the following output −
{ "Name" : "David" } { "Name" : "Bob" }
Advertisements