I'm searching a collection based on some conditions:
const orders = Order.find({ status: 'ACTIVE', isInFlux: true });
Then as I loop through every one of those documents I search Orders again with:
Order.find({ userId: order.userId, status: 'ACTIVE', inFlux: true })
Then I check to see if there are multiple orders belonging to this user that meet these conditions.
Is there a way I can modify my query to get these documents in one shot without having to loop through all of them or possibly an aggregation that would help me?
Looks like you're just trying to conditionally group orders by userID. This will probably do the trick:
db.collection.aggregate([
{
"$group": {
"_id": "$user",
"orders": {
"$push": {
"$cond": [
{
$and: [
{
"$eq": [
"$isInFlux",
true
]
},
{
"$eq": [
"$status",
"active"
]
}
]
},
"$$ROOT",
"$$REMOVE"
]
}
}
}
}
])
Playground: https://mongoplayground.net/p/c8MGdZsjMlJ