How to imitate a loop inside mongodb aggregation query?

Viewed 112

I have a documents in my db like this:

{
  _id: "",
  "name":"myname",
  category: "abc",
  category1: "abc1"
}
{
  _id: ""
  "name":"myname",
  category: "bcd",
  category1: "bcd1",
  category2: "bcd2"
}

Where the category fields can go upto any number it is not predefined but if category2 is present category1 is also there for sure. The hierarchy is like

category -> category1 -> category2 -> ......

Now I if I want to do a search where I match the given text with all categories of a document without knowing the number category present I would need something like a loop.

db.collection('collection', aggregate([
  $match: {
    "category": 'text',
    "category1": 'text',
     .
     .
     so on 
  }
]));

How can this be achieved ?

1 Answers

Assuming the total # of categories is bounded, write one condition per category joined with $or. It might be laborious but it should work.

Related