0

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"] }
        }
      }
    }
  }
]);
2
  • 1
    You need to use $$ 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
    – jQueeny
    Commented Jul 4 at 14:19
  • 1
    This question is similar to: Update MongoDB field using value of another field. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.
    – ray
    Commented Jul 4 at 14:57

0

Browse other questions tagged or ask your own question.