Objects within subarrays filter query in mongodb

Viewed 219

I have struggled with this for a while so cut to the chase:

I have this object in the database

{
  topic: [
    {
      topicName: "Reproduction in plants",
      subTopic: ["Pollination", "Other Topic"]
    },
    {
      topicName: "Plant Cycle",
      subTopic: ["Pollination", "Photosynthesis"]
    },
  ]
}

The problem I am trying to solve here is how to make a query that satisfies the following conditions:

  1. Finds all topic that is within the query of topics
  2. For each of the topic, filter out the results with subtopics inside the topic

So let's say I want this from a query:

  1. Get topics on "Reproduction in plants", of only "Pollination" subtopics
  2. Get topics on "Plant Cycle", of only "Photosynthesis" subtopics

In my current solution:

filterQueries['topic.topicName'] = { $in: ["Reproduction in plants", "Plant Cycle"] };
filterQueries['topic.subTopic'] = { $in: ["Photosynthesis", "Pollination"] };

It easily satisfies most conditions but runs into the edge case, where it will also fetch objects from "Plant Cycle" with "Pollination" subTopic.

How to make a query to do what I want from the conditions above?

I will appreciate any help a lot.

1 Answers
Related