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
Is it possible to exclude nested fields in MongoDB with a wildcard?
Yes, you can exclude nested fields with a wildcard pattern in MongoDB using the aggregation pipeline. This technique uses $objectToArray and $arrayToObject operators to transform nested objects, exclude specific fields, and reconstruct the document.
Syntax
db.collection.aggregate([
{ $project: { "nestedField": { $objectToArray: "$nestedField" } } },
{ $project: { "nestedField.v.fieldToExclude": 0 } },
{ $project: { "nestedField": { $arrayToObject: "$nestedField" } } }
]);
Sample Data
db.demo413.insertOne({
"_id": "101",
"details": {
"Info1": {
"Name": "Chris",
"Age": 21
},
"Info2": {
"Name": "David",
"Age": 23
}
}
});
{ "acknowledged": true, "insertedId": "101" }
Display the current document ?
db.demo413.find();
{ "_id": "101", "details": { "Info1": { "Name": "Chris", "Age": 21 }, "Info2": { "Name": "David", "Age": 23 } } }
Example: Exclude Age Field from All Nested Objects
Remove the "Age" field from all nested objects within "details" ?
db.demo413.aggregate([
{ $project: { "details": { $objectToArray: "$details" } } },
{ $project: { "details.v.Age": 0 } },
{ $project: { "details": { $arrayToObject: "$details" } } }
]);
{ "_id": "101", "details": { "Info1": { "Name": "Chris" }, "Info2": { "Name": "David" } } }
How It Works
-
Step 1:
$objectToArrayconverts the nested object into an array of key-value pairs - Step 2: Use projection to exclude the target field using dot notation on the "v" (value) property
-
Step 3:
$arrayToObjectreconstructs the object from the modified array
Conclusion
Use the $objectToArray and $arrayToObject pipeline combination to exclude nested fields with wildcard behavior. This approach effectively removes the same field from all nested objects within a parent field.
Advertisements
