Hello community,
I have 2 collections with the following schema
- Customers
- _id
- …
- Orders
- _id
- customer_id
- …
The data is modeled as two collections because the number of orders that a customer can have is unbounded, hence I am unable to store orders as an embedded array under Customers.
In the admin dashboard which I am creating, I would like to show a paginated result for the Customers.
- For each customer row, I would like to display the number of orders which the customer has.
- I want to display the number of pages which the admin can scroll through. This requires me to know the total number of customers
To get the number of orders for each customer, and also the total number of customers, I would need to perform an aggregation lookup and count.
{
"$lookup": {
"from": "orders",
"localField": "_id",
"foreignField": "customer_id",
"as": "orders",
}
},
{
"$count": "total_count"
}
I prepared a toy dataset with 1 mil customers, where each customer has 1 order (hence 1 mil orders as well).
I am unable to complete the query above as the query experiences timeout.
These are the options I have considered but none of them seems ideal:
- The option explained above
- Use facets to perform the aggregation and get the count. But the community is advising against this, as the performance is bad as well
- Avoid using aggregation by storing the order count in the Customers record. But this would mean that if the customer has a new order, I would need to update the Customers record as well
- Do not show the total number of customers on the dashboard. But this could result in a bad experience for the admin
- Do not display the total order count for each Customer row. I could explore this, but the admin might need this information.
Just wondering if anyone has a better idea? Thanks!