MongoDB aggregation grouping from multiple documents

445 Views Asked by At

So, in my project, I have 2 collections like these:

Show room collection

{
    "_id":"5fdb3d5e253c844c1bd120c7",
    "name": "Car Showroom 1",  //show room
    "soldUnits": 4,
    "totalUnits": 10,
    "epochTime": 1608210104,
    "market": "area_name_1"  //market
}

These documents are being added every day, also, a show room can be of multiple markets.

Market collection

{
    "id": "area_name_1",
    "name": "Some Place Name",
    "imageURL": "https://example.org/favicon.png"
}

Now,I need to show the data in the following pattern:

    "showroom": {
        "name": "Car Showroom 1",
        "epochTime": 1608210104
    },
    "markets": [
        {
            "area": {
                "id": "area_name_1",
                "name": "Some Place Name",
                "imageURL": "https://example.org/favicon.png"
            },
            "soldUnits": 2,
            "totalUnits": 10
        },
        {
            "area": {
                "id": "area_name_2",
                "name": "Some Place Name",
                "imageURL": "https://example.org/favicon.png"
            },
            "soldUnits": 9,
            "totalUnits": 20
        }
    ]
}

I have used the regular aggregation techniques, but I can't seem to find a solution to this.

The application is a NodeJS application(using NextJS and TypeORM).

Also, I am pretty new to mongodb, so help is really appreciated.

PS. I think some duplicates would be present, so, pointing me what I have missed would be very helpful.

1

There are 1 best solutions below

1
Daniel Chiovitti On

Did you try to use $lookup?

{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}

https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/