I am trying to filter items from a mongoDB document array field that are not equal to the provided value and create a new field with the filtered items using aggregation with $filter method but it is not filtering, instead it shows all the items in array field of the document.
Here is an example:
I want to query the documents that have "reading" in their hobbies and then create another new array field in the document that doesn't include "reading" using aggregation
sample data:
[
{
"_id": 1,
"name": "Alice",
"age": 30,
"hobbies": ["reading","traveling"]
},
{
"_id": 2,
"name": "Bob",
"age": 25,
"hobbies": ["gardening", "photography"]
},
{
"name": "James",
"age": 30,
"hobbies": ["reading", "painting"]
},
{
"_id": 3,
"name": "Charlie",
"age": 35,
"hobbies": ["swimming", "cycling"]
}
]
Expected output:
[
{
"_id": 1,
"name": "Alice",
"age": 30,
"hobbies": ["reading", "painting"], // includes "reading"
"FilteredItems": ["painting"] // Does not include "reading"
},
{
"name": "James",
"age": 30,
"hobbies": ["reading", "painting"], // includes "reading"
"FilteredItems": ["painting"] // Does not include "reading"
}
]
Simply as javascript Array.find((item) => item != unwanted)
I tried $filter method:
db.users.aggregate([
{
$match: {
hobbies: "reading"
}
},
{
$project: {
name: 1,
age: 1,
filteredItems: {
$filter: {
input: "$hobbies",
as: "hobby",
cond: { $eq: ["$hobby", "reading"] }
}
}
}
}
]);
$$
within the filter for your variable name so it will be$$hobby
. Also, if you want to "create another new array field in the document that doesn't include "reading" you should use$ne
instead of$eq
like this