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
How to display a specific field in array using $project in MongoDB and ignore other fields?
To display a specific field from an array in MongoDB and ignore other fields, use the $project operator with $unwind. Set unwanted fields to 0 to exclude them from the output.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{ $match: { "arrayField.field": "value" } },
{ $project: { "_id": 0, "arrayField.unwantedField": 0 } }
]);
Sample Data
db.demo731.insertOne({
"ProductInformation": [
{ "ProductId": "Product-1", "ProductPrice": 80 },
{ "ProductId": "Product-2", "ProductPrice": 45 },
{ "ProductId": "Product-3", "ProductPrice": 50 }
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5eac5efd56e85a39df5f6341")
}
Display All Documents
db.demo731.find();
{
"_id": ObjectId("5eac5efd56e85a39df5f6341"),
"ProductInformation": [
{ "ProductId": "Product-1", "ProductPrice": 80 },
{ "ProductId": "Product-2", "ProductPrice": 45 },
{ "ProductId": "Product-3", "ProductPrice": 50 }
]
}
Example: Display ProductId and Hide ProductPrice
Query to display only ProductId for products with price 80 ?
db.demo731.aggregate([
{ $unwind: "$ProductInformation" },
{ $match: { "ProductInformation.ProductPrice": 80 } },
{ $project: { "_id": 0, "ProductInformation.ProductPrice": 0 } }
]);
{ "ProductInformation": { "ProductId": "Product-1" } }
How It Works
-
$unwindseparates each array element into individual documents -
$matchfilters documents based on array field criteria -
$projectcontrols field visibility: 0 excludes, 1 includes
Conclusion
Use $project with $unwind to selectively display array fields in MongoDB. Set unwanted fields to 0 to exclude them, keeping only the required data in your aggregation results.
Advertisements
