Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB collection query to exclude some fields in find()?
To exclude specific fields from MongoDB query results, set the unwanted fields to 0 in the projection parameter of the find() method. This allows you to retrieve documents while hiding sensitive or unnecessary data.
Syntax
db.collectionName.find(
{ query },
{ fieldToExclude1: 0, fieldToExclude2: 0 }
);
Sample Data
db.demo567.insertMany([
{ "Name": "Chris", "Age": 21 },
{ "Name": "David", "Age": 23 },
{ "Name": "Bob", "Age": 22 },
{ "Name": "Carol", "Age": 20 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e908fa139cfeaaf0b97b57b"),
ObjectId("5e908fa939cfeaaf0b97b57c"),
ObjectId("5e908faf39cfeaaf0b97b57d"),
ObjectId("5e908fb539cfeaaf0b97b57e")
]
}
View All Documents
db.demo567.find();
{ "_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 }
Example: Exclude Age and _id Fields
Query specific documents while excluding Age and _id fields ?
db.demo567.find(
{ "Name": { $in: ["Chris", "Bob"] } },
{ "Age": 0, "_id": 0 }
);
{ "Name": "Chris" }
{ "Name": "Bob" }
Key Points
- Set unwanted fields to
0in the projection parameter to exclude them from results. - The
_idfield is included by default ? explicitly set it to0to exclude it. - Cannot mix inclusion (1) and exclusion (0) projections, except for the
_idfield.
Conclusion
Use field exclusion with fieldName: 0 projection to hide specific fields from query results. This technique improves performance and security by returning only the necessary data from MongoDB collections.
Advertisements
