Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Apply Filter on a Nested Array in a MongoDB

0.00/5 (No votes)
6 Jul 2017 1  
This tip explains how to apply a filter on a nested array in a MongoDB collection.

Background

Let’s say you have a collection in your MongoDB with one of the fields as an array of array.

"categories": [
           [ "Beauty",
            "Makeup",
            "Lips",
            "Lipstick" ]
]

You are asked to filter on this column. If this field would have carried dictionaries, then the query for applying the filter would have been comparatively easier. However, this is not the case.

To achieve this, you need to unwind this column and apply the match operator.

The $unwind Operator

By using the $unwind operator on the target field, it will separate the elements in the array into its own documents and then we match for the element we want.

The below code will apply a filter on a collection ‘ProductMaster’ to get all the documents where ‘categories’ has one or more specified elements mentioned in $in operator.

The query below:

db.getCollection('ProductMaster')
  .aggregate( {$unwind: '$categories'}, {$match: {"categories": {$in: ['Beauty']}}} );

Points of Interest

This morning, I got into a wierd kind of a scenario where I had to apply the filter on an array inside another array. The filter on a string or numeric columns are very straight forward and we have been doing the same from the day we started programming. But this was a unique scenario I came across and the search was on. Every article I was going through was only talking about how to apply a filter on a dictionary carrying column. In a dictionary, you have some relaxation because you can grab a key in order to get its value. In an array of arrays, you don't have any keys. I applied the query meant for dictionaries and started playing around with it. And somehow, I managed to do so and got the desired results.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here