
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Select and Display Specific Field from MongoDB 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" }
Advertisements