Search code examples
javascriptmongodbmatchaggregate

MongoDB Aggregate Match - check if value contains any of the given strings


I have the following types of documents in my mongodb. How can i use a match function to check if the key2 value contains 'Mermaid / Fairy' or 'Superhero'?

  {
    _id: 123,
    key2: [ 'Mermaid / Fairy', 'Superhero' ]
  } 
  {
    _id: 456,
    key2: [ 'Slug']
  } 

This is how i am doing matches for individual words, however i would like to pass in a couple, and if it matches any of them, then it gets returned

    {
      $match: { key2: /.*Superhero.*/ },
    },

Solution

  • Here are a couple of ways ...

    to check if the key2 value contains 'Mermaid / Fairy' or 'Superhero'

    ... by checking if the "$size" of the "$setIntersection" of "$key2" and ["Mermaid / Fairy", "Superhero"]

    db.collection.aggregate([
      {
        "$match": {
          "$expr": {
            "$gt": [
              {
                "$size": {
                  "$setIntersection": [
                    "$key2",
                    ["Mermaid / Fairy", "Superhero"]
                  ]
                }
              },
              0
            ]
          }
        }
      }
    ])
    

    Try it on mongoplayground.net.

    Another way is to use "$reduce" by checking each "$key2" value to see if it is "$in" ["Mermaid / Fairy", "Superhero"].

    db.collection.aggregate([
      {
        "$match": {
          "$expr": {
            "$reduce": {
              "input": "$key2",
              "initialValue": false,
              "in": {
                "$or": [
                  "$$value",
                  {
                    "$in": [
                      "$$this",
                      ["Mermaid / Fairy", "Superhero"]
                    ]
                  }
                ]
              }
            }
          }
        }
      }
    ])
    

    Try it on mongoplayground.net.