I have a data modelling problem and would greatly appreciate any help.
I’ll try to lay down the scenario via a simplified example:
Our data model has profiles
for businesses:
{
name: String,
locations: [ Location{ adm1_id, adm3_id } ],
product: enum.PRO|BASIC
}
We need to query them with and without a location (based on either adm1_id, adm3_id or both), sorting the results so that PRO-product profiles appear first, non-PRO profiles come after that sorted by a specific, separate sort field. This is now done and it works.
Now, approximately 2 days before product launch, the specs changed
We now need to enable multiple locations per profile, but, so that any PRO-products would be location specific, meaning:
- When querying without location (adm1_id or adm3_id), all profiles with any PRO-product will appear first.
- When querying with location, only profiles with PRO-product for the specific
adm1_id
-location will appear first. Profiles with PRO-products for differentadm1_id
-locations are considered non-PRO.
Number two is where my brain snaps.
How would you model, index & query this? I want to avoid resorting to multiple queries if at all possible, since we also have to support pagination via skip, which already makes things very slow, but the best I can come up with is:
{
name: String,
locations: [Location{adm1_id, adm3_id, product}]
}
…but, per my understanding, this requires two queries, one two fetch profiles which have PRO-product, and another to fetch the rest. I’m not very experienced with aggregates, maybe there’s a solution hidden there. From the little I could gather, maybe something like…
{
$match // query
$unwind // separate docs based on `locations`
$filter // filter based on...?
...?
}
…could work?
Thanks for reading this far.