- 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
Select special fields rather than all in MongoDB
For this, simply use find(). Set the fields you don’t want to select to 0. Let us create a collection with documents −
> db.demo269.insertOne({StudentId:101,StudentSubject:"MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5e481caa1627c0c63e7dbab4") } > db.demo269.insertOne({StudentId:102,StudentSubject:"Java"}); { "acknowledged" : true, "insertedId" : ObjectId("5e481cb11627c0c63e7dbab5") } > db.demo269.insertOne({StudentId:103,StudentSubject:"MongoDB"}); { "acknowledged" : true, "insertedId" : ObjectId("5e481cb21627c0c63e7dbab6") } > db.demo269.insertOne({StudentId:104,StudentSubject:"C"}); { "acknowledged" : true, "insertedId" : ObjectId("5e481cb21627c0c63e7dbab7") }
Display all documents from a collection with the help of find() method −
> db.demo269.find();
This will produce the following output −
{ "_id" : ObjectId("5e481caa1627c0c63e7dbab4"), "StudentId" : 101, "StudentSubject" : "MySQL" } { "_id" : ObjectId("5e481cb11627c0c63e7dbab5"), "StudentId" : 102, "StudentSubject" : "Java" } { "_id" : ObjectId("5e481cb21627c0c63e7dbab6"), "StudentId" : 103, "StudentSubject" : "MongoDB" } { "_id" : ObjectId("5e481cb21627c0c63e7dbab7"), "StudentId" : 104, "StudentSubject" : "C" }
Following is the query to select only specific fields rather than all −
> db.demo269.find({},{"StudentId":0,_id:0});
This will produce the following output −
{ "StudentSubject" : "MySQL" } { "StudentSubject" : "Java" } { "StudentSubject" : "MongoDB" } { "StudentSubject" : "C" }
Advertisements