Du kan använda cond i $project eller $expr i $match steg som:
collectionName.aggregate([
{
$match: {
$expr: {
$cond: {
if: {
$gt: [
"$audiPrice",
null
]
},
then: {
$and: [
{
$gte: [
"$audiPrice",
price * 0.25
]
},
{
$lte: [
"$audiPrice",
price * 1.75
]
}
]
},
else: {
$and: [
{
$gte: [
"$price",
price * 0.25
]
},
{
$lte: [
"$price",
price * 1.75
]
}
]
}
}
}
}
}
])
Här kontrollerar du först om fältet audiPrice inte är null och utför sedan matchningen på den nyckeln annars på prisnyckeln.