Group by nested array object and group items to array

I have an array like this:

[
    {
        name: "product1",
        cat: [
            {
                title: "cat1"
            },
            {
                title: "cat2"
            }
        ],
        price: 123
    },
    {
        name: "product2",
        cat: [
            {
                title: "cat1"
            }
        ],
        price: 100
    }
]

How do I convert to this:

[
    {
        _id: "cat1",
        items: [
            {name: "product1", price: 123},
            {name: "product2", price: 100}
        ]
    },
    {
        _id: "cat2",
        items: [
            {name: "product1", price: 123}
        ]
    }
]

I know I can use $group operator but I only get _id field, please help me.

Is that an array of documents or an array within a document?

I’d first $unwind the cat field, then use $group to reform into your needed format.

If you have multiple in a document then you’ll need to unwind that first.

Run in steps, unwind first, look at the output, then apply the group on top of that.

1 Like

Thank you so much. This is my code

const products = await _shop_product.aggregate([
                { $sort: { _id: -1 } },
                { $match: filter },
                { $project: { _id: 0, cat_name: "$categories.name", product_list: { name: "$name", price: "$price" } } },
                { $unwind: "$cat_name" },
                { $group: { _id: "$cat_name", product_list: { $push: { name: "$product_list.name", price: "$product_list.price" } } } },
                { $project: { product_list: { $slice: ["$product_list", 6] } } }
            ])

It’s working. Thanks

1 Like

Excellent, glad you got it working!

Good luck!

1 Like