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.