I have a MongoDB aggregation query in which I have the following:
{ $match: { version: versionNumber }
The 'versionNumber' is an optional input parameter to the aggreagation. If this versionNumber is not provided, then I do not want this match to be performed.
Currently, if the versionNumber is not supplied, the match still happens and I get a blank query output.
Is there a way in Mongo to do this? Thanks!
I am not sure what will be the value in versionNumber when its not provided (optional), lets assume versionNumber will be any from "" or undefined or null,
versionNumebr is not available then it will skip and when its available then it will match $eq condition[null, "", "undefined"], 0 zero or anything you wanted to skip {
$match: {
$expr: {
$cond: [
{ $in: [versionNumber, [null, "", "undefined"]] },
true,
{ $eq: ["$version", versionNumber] }
]
}
}
}
versionNumebr will be always single possible value "" then you can use $eq instead of $in, {
$match: {
$expr: {
$cond: [
{ $eq: [versionNumber, ""] },
true,
{ $eq: ["$version", versionNumber] }
]
}
}
}
Playground
There is a way to do that, yes, but it should be done in the application code. When building the pipeline array to pass to the query, only include the $match stage if the necessary information is provided.
var pipeline=[]
if (versionNumber) pipeline.push( {$match: {version: versionNumber }} )
pipeline.push( ... Other Stages ... )
db.collection.aggregate(pipeline)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With