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
Using addFields pipeline and run with the MongoDB filter operator
The $addFields pipeline stage combined with the $filter operator allows you to add new fields or modify existing ones by filtering array elements based on specific conditions.
Syntax
db.collection.aggregate([
{
$addFields: {
"fieldName": {
$filter: {
input: "$arrayField",
as: "item",
cond: { condition }
}
}
}
}
]);
Sample Data
Let us first create a collection with documents ?
db.demo118.insertOne({
"Id": "101",
"Name": "Chris",
"Subjects": [
"MySQL",
"MongoDB",
"Java"
],
"Details": [
{
"Name": "David",
"S": "MongoDB"
},
{
"Name": "Bob",
"S": "Python"
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e2f0c0cd8f64a552dae6364")
}
Display all documents from a collection with the help of find() method ?
db.demo118.find();
{
"_id": ObjectId("5e2f0c0cd8f64a552dae6364"),
"Id": "101",
"Name": "Chris",
"Subjects": ["MySQL", "MongoDB", "Java"],
"Details": [
{"Name": "David", "S": "MongoDB"},
{"Name": "Bob", "S": "Python"}
]
}
Example: Filter Details Based on Subjects
Following is the query to use $addFields pipeline to filter Details array elements that match values in the Subjects array ?
db.demo118.aggregate([
{
$addFields: {
"Details": {
$filter: {
input: "$Details",
as: "out",
cond: { $in: ["$$out.S", "$Subjects"] }
}
}
}
}
]).pretty();
{
"_id": ObjectId("5e2f0c0cd8f64a552dae6364"),
"Id": "101",
"Name": "Chris",
"Subjects": [
"MySQL",
"MongoDB",
"Java"
],
"Details": [
{
"Name": "David",
"S": "MongoDB"
}
]
}
How It Works
-
$addFieldscreates or replaces the existing "Details" field -
$filterprocesses each element in the Details array -
$inchecks if the "S" field value exists in the Subjects array - Only matching elements (David with "MongoDB") are retained
Conclusion
The $addFields stage with $filter provides a powerful way to modify array fields by keeping only elements that meet specific criteria, enabling dynamic field transformations in aggregation pipelines.
Advertisements
