Match any item in array to key in object greater than 0

Hello!
I have many documents like this in the collection

{
  "other_info" : "foo",
  "table": {
      "name1": 1,
      "name2": 1,
      "name3": 1,
      "name4": 0,
      "name5": 1,
      "name6": 1,
      "name7": 1
  }
}
{
  "other_info" : "bar",
  "table": {
      "name1": 0,
      "name2": 1,
      "name3": 4,
      "name4": 1
  }
}

I have an array NAMES= [“name4”,“name5”,“name7”]

i want to query it so that i find all documents that have any of the values in the list as a key where its value is greater than 0

Match ANY item in NAMES where value of found NAME $gt 0

How can i accomplish this?

The main reason having dynamic field names is not recommended is that it complicates simple things like this.

With the attribute pattern this is easy to solve. A simple query like

"tables.v" : { "$gt" : 0 }

would suffice.

One way to do it with your current schema would be to use aggregation with a $set stage that uses $objectToArray to essentially dynamically convert your table into the attribute pattern. The a $match that uses the simple query above should work.

Another way is to use map on NAMES to create a big “$or” query that would end up looking like:

{ "$or" : [
    { "table.name4" : { "$gt" : 0 } } ,
    { "table.name5" : { "$gt" : 0 } } ,
    { "table.name7" : { "$gt" : 0 } }
] }