I have two collections:
USERS:
{
{"_id": 1, "orders": [1,2]},
{"_id": 2, "orders": [3]},
{"_id": 3, "orders": [4,5]}
}
ORDERS:
{
{"_id": 1, "paid": true},
{"_id": 2, "paid": false},
{"_id": 3, "paid": true},
{"_id": 4, "paid": false},
{"_id": 5, "paid": false}
}
How can I use MongoDB\Driver in php select all entries from the USERS collection containing at least one paid order? At the moment, I am pulling both collections incide php, and when using the comparison of arrays just filter the collection of users.
My code at this moment:
$users = _mongo_::collection('USERS')->find([]);
$paid_orders = _mongo_::collection('ORDERS')->find(['paid' => true]);
$paid_orders_ids = array_column($paid_orders, '_id');
$filtered_users = array_filter($users, function ($user) use ($paid_orders_ids) {
return (boolean) array_intersect($user['orders'], $paid_orders_ids);
});
The question is, can I get the filtered list of users right away with just one MongoDB\Driver query?