skip to Main Content

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.*/ },
    },

2

Answers


  1. you can use this aggregate

    itemsSchema.aggregate([
      {
        $match: {
          "key2": {
             $in: [
               "Mermaid / Fairy",
               "Superhero"
             ]
           }
       }
     }])
    
    Login or Signup to reply.
  2. 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.

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