'Mongodb Aggregate ObjectToArray on property consiting of array

I need to retrieve a list of distinct properties of a type using MongoDB Aggregation function. The data looks like this

{
 "name" :"ABC",
 "rates:" 
  [
    {"weight", "0.5",
           "A": "1000",
           "B": "2000",
           "C": "3000"
    },
    {"weight", "1",
           "A": "1000",
           "B": "2000",
           "C": "3000",
           "D": "6000",
    }
  ]
}

The desired outcome double to ["A", "B", "C", "D"]. In the perfect scenario it would be nice to get only the properties with specific type. Can you please suggest how would I achieve this? Thank you.



Solution 1:[1]

Query

  • reduce to collect the distinct values, using setUnion
  • $objectToArray to convert each document to key,value pairs, here we need the keys only
  • filter to remove the key weight(we only care for the others (A,B,C ...)

*if this isn't what you want, if you can give the expected output in json for the sample documents Test code here

aggregate(
  [{
      "$set": {
        "d-types": {
          "$reduce": {
            "input": "$rates",
            "initialValue": [],
            "in": {
              "$setUnion": ["$$value",
                {
                  "$map": {
                    "input": {
                      "$objectToArray": "$$this"
                    },
                    "in": "$$type.k",
                    "as": "type"
                  }
                }
              ]
            }
          }
        }
      }
    },
    {
      "$project": {
        "_id": 0,
        "d-types": {
          "$filter": {
            "input": "$d-types",
            "cond": {
              "$ne": ["$$this", "weight"]
            }
          }
        }
      }
    }
  ])

If you need only some of the distinct, you can use this filter like that. To keep only "B" and "C" if they appear as types, or you can use $not to reject "B", "C" from the results.

{
  "$filter": {
    "input": "$d-types",
    "cond": {
      "$and": [{
          "$ne": ["$$this", "weight"]
        },
        {
          "$in": ["$$this", ["B", "C"]]
        }
      ]
    }
  }
}

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Dharmaraj