
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 Specific Columns in MongoDB Query
To select specific columns, you can ignore the rest of them i.e. to hide those columns, set them to 0. Let us first create a collection with documents −
> db.demo415.insertOne({"ClientName":"Robert","ClientCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5e72329db912067e57771adc") } > db.demo415.insertOne({"ClientName":"David","ClientCountryName":"UK"}); { "acknowledged" : true, "insertedId" : ObjectId("5e7232acb912067e57771add") } > db.demo415.insertOne({"ClientName":"Bob","ClientCountryName":"AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5e7232b4b912067e57771ade") }
Display all documents from a collection with the help of find() method −
> db.demo415.find();
This will produce the following output −
{ "_id" : ObjectId("5e72329db912067e57771adc"), "ClientName" : "Robert", "ClientCountryName" : "US" } { "_id" : ObjectId("5e7232acb912067e57771add"), "ClientName" : "David", "ClientCountryName" : "UK" } { "_id" : ObjectId("5e7232b4b912067e57771ade"), "ClientName" : "Bob", "ClientCountryName" : "AUS" }
Following is the query to select specific columns. Here, we have ignored rest of the columns to display the column “ClientCountryName” −
> db.demo415.find({},{_id:0,ClientName:0});
This will produce the following output −
{ "ClientCountryName" : "US" } { "ClientCountryName" : "UK" } { "ClientCountryName" : "AUS" }
Advertisements