Filter subdocuments by conditions in Mongo Charts Query


I want to filter subdocuments in Mongo Charts Query.

I have a document with a field and a field of array of documents like:

‘n’: 1,
subdocuments_array: [sub_1, sub_2,…,sub_n],
subdocuments_array:[sub_1, sub_2,…,sub_n],
} and so on.

These sub_n have the following form:

‘value’: some number
‘flag1’: 0 or 1,
‘flag2’: 0 or 1

I want to use only the subdocuments with flag1 and flag 2 equal to 1.

I’ve tried to use {‘sub_n.flag’: {$ne: 0}} but this is filtering the entire document when there is a subdocument with flag equal to 0.

I hope you can help me.

Thank you.

Hi @Fryderyk_Chopin -

The trick here is to use $unwind on the array before you filter. That will result in a new document being created for each array element, which you can then filter with a $match stage.

Based on your sample docs, the full pipeline would be something like:

  { $unwind: "$subdocuments_array" },
  { $match: { "subdocuments_array.flag1":1, "subdocuments_array.flag2":1 } }
1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.