Click here to Skip to main content
15,891,253 members
Articles / Database Development / MongoDB
Tip/Trick

Apply Filter on a Nested Array in a MongoDB

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
6 Jul 2017CPOL1 min read 17.1K  
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.

JavaScript
"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:

SQL
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --