'MongoDb query using Aggregate and grouping funciton on Nested Columns

MongoDb query using Aggregate and grouping funciton on Nested Columns. Need to find all the rule for same values like AllValues have keys(Col2,Col3 and Col4).

MongoDB collection

[{
  "Ruler": {
    "Col1": {
      "Rule": "Y_if_anyone_is_Y"
    },
    "Col2": {
      "Rule": "AllValues"
    },
    "Col3": {
      "Rule": "AllValues"
    },
    "Col4": {
      "Rule": "Y_if_anyone_is_Y"
    },
    "Col5": {
      "Rule": "AllValues"
    }
}]

Output

AllValues = [Col2, Col3, Col5]
Y_if_anyone_is_Y = [Col1, Col4]

code tried

for _each in collection_name.aggregate([{ "$group" :
                                              { "_id" :
                                                    { "SET_ID": "$Ruler"}
                                              }
                                        }
                                    ]):
    print("stewardAction-",_each['_id']['SET_ID'])


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source