0

I have a collection called shows, with documents as:

       {
            "url": "http://www.tvmaze.com/shows/167/24",
            "name": "24",
            "genres": [
                "Drama",
                "Action"
            ],
            "runtime": 60
        },
        {
            "url": "http://www.tvmaze.com/shows/4/arrow",
            "name": "Arrow",
            "genres": [
                "Drama",
                "Action",
                "Science-Fiction"
            ],
            "runtime": 60
        }

I wanted to search shows with genre 'Action' and project the result array as

   {
        "url": "http://www.tvmaze.com/shows/167/24",
        "name": "24",
        "genres": [
            "Action" // I want only the matched item in 
         //my result array
        ],
        "runtime": 60
    } , //same for the second doc as well

If I use

db.shows.find({genres:'Action'}, {'genres.$': 1});

It works but the same does not work in aggregate method with $project

Shows.aggregate([
      {
        $match: { 'genres': 'Action'}
      },
      {
        $project: {
          _id: 0,
          url: 1,
          name: 1,
          runtime: 1,
          'genres.$': 1
        }
      }
]);

this is the error I get on this aggregate query

Invalid $project :: caused by :: FieldPath field names may not start with '$'."
7
  • 1
    The $ projection will work only on find methods, you can use $filter aggregation operator in aggregation query. Commented Jun 18, 2021 at 7:52
  • Does this answer your question? How to filter array in a mongodb query Commented Jun 18, 2021 at 8:00
  • @turivishal, no it did not answer, also what if I am using regex to match the genre 'Action', then how would I do it while projecting, it might not be the exact match. Commented Jun 18, 2021 at 8:07
  • You can use $regexMatch operator inside $filter. Commented Jun 18, 2021 at 8:15
  • 1
    just remove / slashes from both match string. Commented Jun 18, 2021 at 8:30

1 Answer 1

0
db.collection.aggregate([
  {
    $match: {
      "genres": {
        $regex: "/^action/",
        $options: "im"
      }
    }
  },
  {
    $project: {
      _id: 0,
      url: 1,
      name: 1,
      runtime: 1,
      genres: {
        $filter: {
          input: "$genres",
          as: "genre",
          cond: {
            $regexMatch: {
              input: "$$genre",
              regex: "/^action/",
              options: "im"
            }
          }
        }
      }
    }
  }
])

Here is how I solved it, Thanks @turivishal for the help

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.