How to add a document, with all the diferent keys, to the returned documents

I’m implementing a proof of concept were I have a collection with objects that have different schemas, but for example in a query I get these results using the $match pipeline stage :

 {
        "_id": "61bb24d6aaee34d23dcf9782",
        "price": 10250,
        "brand": "audi",
        "model": "a4",
        "fuel": "diesel",
        "power": 150,
        "type": "sedan",
        "gearbox": "manual",
        "color": "blue",
    },
    {
        "_id": "62178eb749256d30c944f3cf",
        "price": 15500,
        "brand": "toyota",
        "model": "rav4",
        "fuel": "gas",
        "power": 150,
        "type": "suv",
        "gearbox": "automatic",
        "color": "red",
    },
    {
        "_id": "61bb3b73aaee34d23dcf9d82",
        "price": 11500,
        "brand": "bmw",
        "model": "318",
        "fuel": "diesel",
        "mileage": 224999,
        "power": 143,
        "type": "van",
        "gearbox": "automatic",
        "color": "yellow",
    },

how can I get MongoDB to return all those documents plus an object that has all the distinct qualitative (not quantitative) keys and for each key, all its possible values (of the current objects) I would like the output to be like this:

 {
        "_id": "61bb24d6aaee34d23dcf9782",
        "price": 10250,
        "brand": "audi",
        "model": "a4",
        "fuel": "diesel",
        "power": 150,
        "type": "sedan",
        "gearbox": "manual",
        "color": "blue",
    },
    {
        "_id": "62178eb749256d30c944f3cf",
        "price": 15500,
        "brand": "toyota",
        "model": "rav4",
        "fuel": "gas",
        "power": 150,
        "type": "suv",
        "gearbox": "automatic",
        "color": "red",
    },
    {
        "_id": "61bb3b73aaee34d23dcf9d82",
        "price": 11500,
        "brand": "bmw",
        "model": "318",
        "fuel": "diesel",
        "mileage": 224999,
        "power": 143,
        "type": "van",
        "gearbox": "automatic",
        "color": "yellow",
    },
{
        "brand": [audi,toyota,bmw],
        "fuel":[diesel,gas],
        "type":[sedan,suv,van],
        "gearbox":[manual,automatic],
        "color": [blue,red,yellow],
}

I’ve reed de docs from the beginning to end, and it seems that the aggregation pipeline does not have any stage that enables this kind of behavior, I’m I right? Or there’s some way to get it?

Thanks

Hello @Luis_Figueira, welcome to the forum!

You can use the aggregation $group stage to get the following output. You can apply the Accumulator Operators within the $group; for example, $push and $addToSet are useful.

{
        "brand": [audi,toyota,bmw],
        "fuel":[diesel,gas],
        "type":[sedan,suv,van],
        "gearbox":[manual,automatic],
        "color": [blue,red,yellow],
}
1 Like

Thanks @Prasad_Saya,

I’ll explore and try the resources you mentioned and will give you some feedback afterwards.