- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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" }
- Related Articles
- MySQL query to fetch only a single field on the basis of boolean value in another field
- Querying only the field name and display only the id in MongoDB?
- How to query on list field in MongoDB?
- Return query based on date in MongoDB?
- MongoDB query to fetch a document that does not have a particular field?
- How to run MongoDB query to update only a specific field value?
- MongoDB query to fetch array values
- MongoDB query select and display only a specific field from the document?
- MongoDB query to fetch a specific document rom documents with field value set using NumberInt()?
- Fetch specific field values in MongoDB
- Query MongoDB with “like” implementation on name and email field beginning with a specific letter?
- MongoDB query to find on field combination of FirstName and LastName?
- MongoDB aggregation to fetch documents with specific field value?
- MongoDB query by sub-field?
- MongoDB query to update a MongoDB row with only the objectid

Advertisements