Jay Park
Jay Park

Reputation: 348

How to check if string value of a field is a substring of another field in MongoDB

1.Assuming I have a collection named test and contain three documents. The structure of document would be like:

{
       Text: " String is string",
       Text1:  "string"
       
       
 },

{
       Text: "Good is good",
       Text1: "good"
       
       
 } 
  1. How can I write a aggregation query to find all the documents where Text contains Text1 (case insensitive)?

Upvotes: 1

Views: 1220

Answers (1)

Programmer Analyst
Programmer Analyst

Reputation: 919

you can make use of regular expression to match the text1 in text sample code: https://mongoplayground.net/p/d2WJO7sG1jO

    db.collection.aggregate([
  {
    $addFields: {
      matched: {
        $regexMatch: {
          "input": "$Text",
          "regex": "$Text1",
          options: "i"
        }
      }
    }
  },
  {
    "$match": {
      matched: true
    }
  },
  {
    "$project": {
      matched: 0
    }
  }
])

Here we add additional field by checking if Text1 is there in Text with case insensitive. if match found then only we return the matched results. Note here we just check on self document we are not matching across the documents.

Upvotes: 2

Related Questions