Skip to content
Advertisement

Speed Up and Simplify MongoDB Aggregate Function

I have the following function, which is quite complicated, but i’m hoping someone might be able to understand it help me simplify/speed it up.

In this function i end up with an array that contains a list of primaryStores and the number of products coming from each one to my group of stores. However, it only counts the products, if that store has an accepted connection with the particular primary store in question. (Some might have an accepted connection to one and not the other yet)

I will try and explain how it works:

I pass into the function a list of storeIDs. I loop through each one to find out which primary stores each one has an accepted connection with. Out of those with an accepted connection, i just get the store ID. I then find out what products are in my store, and get the product IDs and the linked ID connecting them to my store. I then begin my aggregate function which starts off by finding which of my products have a connection to another store. I then look up the other stores info to get the store ID and filter to only get ones i am connected to. I then project this and group by store id/name and get the total number of products coming from each primary store and an array containing a list of all the products from each one. I push each connected primaryStore for each of my main stores into an array called ‘allFeederStores’.

As i am looping through each of my main stores one at a time to get this information. At the end I have a reduce function which combines any duplicating primaryStores that appear in my array, and concatenate the total products. This provides my with an overview of where the majority of my products are coming from for all of my main stores.

I am trying to get rid of the for loop at the beginning, so i don’t have to loop through each store at once. But i can’t figure out, how i can check a signed connection exists between the two individual stores without doing them seperate.

It’s not likely anyone will understand this, but if anyone does and can help I would much appreciate it!

Below is my code:

JavaScript

I have added some sample data below. In this case MainStore1 has a signed connection with PrimaryStore1 but not PrimaryStore1 (so any products coming from that primary store won’t be counted for this main store) However MainStore2 has a signed connection with both PrimaryStore1 and PrimaryStore2, (so any products coming from both those primary stores will be counted for this main store)

JavaScript

Expected output is something like this:

JavaScript

Advertisement

Answer

If I understand your logic correctly, this aggregation pipeline returns the number of, and list of, products for each "primary_store" where the products come from a “signed” "main_store".

JavaScript

Try it on mongoplayground.net.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement