Skip to content
Advertisement

Is there a way to search through embedded arrays using aggregate pipeline in MongoDB?

I need to search through all the arrays within the categories field to find if the product belongs in the ‘T-Shirt’ category, is there a way to search through all the arrays within the category field?

Any help would be appreciated.

Here is what I have tried so far

JavaScript

Here is an example of one of the documents:

JavaScript

Advertisement

Answer

Sure. You may use the unwind operator in order to get rid of nested arrays.

This operator allows you to have as many separate documents as items in the selected array. For example, having this document:

JavaScript

If you use unwind on the categories field:

db.products.aggregate( [ { $unwind : "$categories" } ] )

You will get 3 almost similar documents, where only categories are different (1 doc for each item in top level array):

JavaScript

Now you may use the $in operator or other ways for querying and filtering via categories.

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