skip to Main Content

I have a collection of documents where each of the documents may have an array of teamsIds like:

{
  "id": 1,
  "teamsIds": ["team_a", "team_b"]
}

I’m trying to write an Aggregation (doing $match stage before) that will $project the documents and return objects like:

{ 
  "id": 1,
  "matchingFilter": true
}

where matchingFilter should be true when teamsIds does contain any of the teams I’m checking for. In the case of the document above, I need matchingFilter to be true when searching for teams: ["team_c", "team_a"] because it has assigned "team_a". What would be the simplest way to achieve it? I can’t use $elemMatch in the Aggregation pipeline, is there an equivalent I could use?

2

Answers


  1. You can use $match to look for documents that have a teamsIds element value $in a user supplied array of values then just $set the matchingFilter: true to all matching document like so:

    db.collection.aggregate([
      {
        $match: {
          teamsIds: {
            $in: [
              "team_a",
              "team_c"
            ]
          }
        }
      },
      {
        $set: {
          matchingFilter: true
        }
      },
      {
        $project: {
          _id: 0,
          id: 1,
          matchingFilter: 1
        }
      }
    ])
    

    See HERE for a working example.

    Login or Signup to reply.
  2. The canonical implementation of your expected set intersection behaviour is using $setIntersection

    db.collection.aggregate([
      {
        "$match": {
          // your match here
          
        }
      },
      {
        "$project": {
          "id": 1,
          "matchingFilter": {
            "$ne": [
              [],
              {
                "$setIntersection": [
                  "$teamsIds",
                  // your input array here
                  [
                    "team_c",
                    "team_a"
                  ]
                ]
              }
            ]
          }
        }
      }
    ])
    

    Mongo Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search