aneroid
(Anirudh Dutt)
3
Not necessarily
.
Let’s say you want to ignore the problematic documents but still want to do the search on valid documents: Join the type=array and lastValue=1 checks with an $and so that only documents which have "$TransactionStatus.StatusType" as an array get checked.
db.transaction.find({
$expr: {
$and: [
{
"$eq": [
{ "$type": "$TransactionStatus.StatusType" },
"array"
]
},
{
"$eq": [
{ "$arrayElemAt": ["$TransactionStatus.StatusType", -1] },
1
]
}
]
}
})
Mongo Playground example D
You could also make your query more permissive by accommodating the incorrect structure (those non-arrays) by wrapping that $and clause with an $or, like this. But that could lead to errors when processing the result documents in your application code, where it’s expected to be an array.
Consider adding Schema Validation to prevent future inserts or updates which incorrectly change the structure.
1 Like