I am searching for a query to use in the $match
stage of my aggregation that works similarly to the one mentioned in this particular question on Stack Overflow, but with a twist...
- If a specific field (in my case, it's called rank) does not exist in the document, I want to include it in the results.
- However, if the field exists, I want to apply a
$operator
condition (such as$max
in my case) to this field and include all documents that meet this condition in the results.
Check out this example collection on MongoPlayground.
The desired result should look like this:
[
{
"method": 3,
"item": 1,
"rank": 3 // This document has the rank field and meets the {rank: $max} condition
},
{
"method": 4,
"item": 1 // This is included because the document doesn't have the rank field at all
},
{
"method": 5,
"item": 1 // This document is also included for the same reason as above
}
]
Here are some approaches I've already attempted:
{
$match: {
$or: [
{item: id, rank: {$exists: true, $max: "$rank"}},
{item: id, rank: {$exists: false}}
]
}
}
UPDATE: Currently, I might not be restrained to just using the
$match
stage. The$project
stage could also prove useful after the initial match, allowing me to retrieve every document based on theid
regardless of whether or not they have therank
field. Then, during the$project
stage, I can differentiate based on the existence of the rank field.