You may not yet be aware of the $cond
operator which works as a ternary condition. So basically if a condition given a as a first argument is true
then use the value in the next argument. If the condition evaluates to false
then use the value in the last condition in the operator.
This turns out to be perfect as you already have an indicator of true or false to determine the field
db.orders.aggregate([
{ "$project": {
"typeID": 1,
"bestBuy": { "$cond": [
"$buyOrder",
"$price",
null
]},
"bestSell": { "$cond": [
"$buyOrder",
null,
"$price"
]}
}},
{ "$group": {
"_id": "$typeID",
"bestBuy": { "$max": "$bestBuy" },
"bestSell": { "$min": "$bestSell" }
}},
{ "$sort": { "_id": 1 } }
])
So the use of $max
and $min
here can negate the null
values in the results where the condition was not met.