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?
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 containingk
andv
properties.
cond
: With$regexMatch
operator to filter the document with the value ofv
matching the regex pattern.
db.collection.find({
$expr: {
$ne: [
{
$filter: {
input: {
$objectToArray: "$status"
},
cond: {
$regexMatch: {
input: "$$this.v",
regex: "INACTIVE",
options: "i"
}
}
}
},
[]
]
}
})