

- 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 collection query to exclude some 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" }
- Related Questions & Answers
- MongoDB query to exclude both the fields with FALSE
- MongoDB query to find last object in collection?
- MongoDB query to sum specific fields
- MongoDB query to update selected fields
- Is it possible to exclude nested fields in MongoDB with a wildcard?
- MySQL query to exclude some of the values from the table
- MongoDB query to rename a collection?
- Get all fields names in a MongoDB collection?
- MongoDB query condition to compare two fields?
- MongoDB query to update only certain fields?
- Query MongoDB collection starting with _?
- How to retrieve all nested fields from MongoDB collection?
- MongoDB query for fields in embedded document?
- MongoDB query to find a specific city record from a collection
- How to re-map the fields of a MongoDB collection?
Advertisements