
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
MongoDB Collection Query to Exclude Fields in Find
Set the fields you don’t want to include as 0 as in the below syntax. Here, we have set fields “yourFieldName1” and “yourFieldName2” as 0 −
db.yourCollectionName.find(yourQuery, {yourFieldName1:0,yourFieldName2:0});
To understand the above syntax, let us create a collection with documents −
> db.demo567.insertOne({"Name":"Chris",Age:21});{ "acknowledged" : true, "insertedId" : ObjectId("5e908fa139cfeaaf0b97b57b") } > db.demo567.insertOne({"Name":"David",Age:23});{ "acknowledged" : true, "insertedId" : ObjectId("5e908fa939cfeaaf0b97b57c") } > db.demo567.insertOne({"Name":"Bob",Age:22});{ "acknowledged" : true, "insertedId" : ObjectId("5e908faf39cfeaaf0b97b57d") } > db.demo567.insertOne({"Name":"Carol",Age:20});{ "acknowledged" : true, "insertedId" : ObjectId("5e908fb539cfeaaf0b97b57e") }
Display all documents from a collection with the help of find() method −
> db.demo567.find();
This will produce the following output −
{ "_id" : ObjectId("5e908fa139cfeaaf0b97b57b"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5e908fa939cfeaaf0b97b57c"), "Name" : "David", "Age" : 23 } { "_id" : ObjectId("5e908faf39cfeaaf0b97b57d"), "Name" : "Bob", "Age" : 22 } { "_id" : ObjectId("5e908fb539cfeaaf0b97b57e"), "Name" : "Carol", "Age" : 20 }
Following is the query to exclude some fields in find() −
> db.demo567.find({Name:{$in:["Chris","Bob"]}}, {Age:0,_id:0});
This will produce the following output −
{ "Name" : "Chris" } { "Name" : "Bob" }
Advertisements