

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 select and display only a specific field from the document?
Let us first create a collection with documents −
> db.querySelectDemo.insertOne({UserId:100,UserName:"Chris",UserAge:25}); { "acknowledged" : true, "insertedId" : ObjectId("5ce90eb478f00858fb12e90e") } > db.querySelectDemo.insertOne({UserId:101,UserName:"Robert",UserAge:26}); { "acknowledged" : true, "insertedId" : ObjectId("5ce90ec578f00858fb12e90f") } > db.querySelectDemo.insertOne({UserId:103,UserName:"David",UserAge:27}); { "acknowledged" : true, "insertedId" : ObjectId("5ce90ed478f00858fb12e910") }
Following is the query to display all documents from a collection with the help of find() method −
> db.querySelectDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5ce90eb478f00858fb12e90e"), "UserId" : 100, "UserName" : "Chris", "UserAge" : 25 } { "_id" : ObjectId("5ce90ec578f00858fb12e90f"), "UserId" : 101, "UserName" : "Robert", "UserAge" : 26 } { "_id" : ObjectId("5ce90ed478f00858fb12e910"), "UserId" : 103, "UserName" : "David", "UserAge" : 27 }
Following is the query to include only a specific field by setting it to TRUE in find() −
> db.querySelectDemo.find({},{_id:0,UserName:true});
This will produce the following output −
{ "UserName" : "Chris" } { "UserName" : "Robert" } { "UserName" : "David" }
- Related Questions & Answers
- MongoDB query to update a specific document from a collection
- MongoDB query to pull a specific value from a document
- How to select MongoDB document that does not consist a specific field?
- MongoDB query to remove a specific document
- Querying only the field name and display only the id in MongoDB?
- How to run MongoDB query to update only a specific field value?
- Update only a specific value in a MongoDB document
- Display only a single field from all the documents in a MongoDB collection
- MongoDB query to return only embedded document?
- Filter specific values from a MongoDB document
- How to select objects where an array contains only a specific field in MongoDB?
- Selecting only a single field from MongoDB?
- MongoDB query to fetch a specific document rom documents with field value set using NumberInt()?
- Find the document by field name with a specific value in MongoDB?
- Insert MongoDB document field only when it's missing?
Advertisements