Search code examples
mongodbmongodb-querymongodb-compass

How to search a string in an object in mongodb compass


I have data stored in this form

"status": { "634feb9a5723003699a87e1e": "ACTIVE", "634ff0b95723003699a88054": "ACTIVE"   }

this status is an object. Here you can see the keys are mongodb objectIds, I want to find those documents where any child of the status has value "INACTIVE".

I've tried using regex in mongodb compass like this

{status:/"INACTIVE"/i}

But I think this method only works in string array. Please tell me how can I do that with objects?


Solution

  • As status is an object with dynamic keys, filtering the status object containing the "INACTIVE" value without the concern of dynamic keys:

    $expr - Using aggregation operator.

    $ne - Compare the result is not equal to an empty array.

    $filter:

    input: $objectToArray - Convert the object into an array with objects containing k and v properties.

    cond: With $regexMatch operator to filter the document with the value of v matching the regex pattern.

    db.collection.find({
      $expr: {
        $ne: [
          {
            $filter: {
              input: {
                $objectToArray: "$status"
              },
              cond: {
                $regexMatch: {
                  input: "$$this.v",
                  regex: "INACTIVE",
                  options: "i"
                }
              }
            }
          },
          []
        ]
      }
    })
    

    Demo @ Mongo Playground