Home > database >  How to show products categorized in MongoDB?
How to show products categorized in MongoDB?

Time:03-01

I have a MongoDB collection name as 'products', which have these documents:

{productName: "ABC", category: "cat1"}
{productName: "DEF", category: "cat2"}
{productName: "GHI", category: "cat3"}
{productName: "JKL", category: "cat1"}
{productName: "MNO", category: "cat2"}
{productName: "PQR", category: "cat3"}

I want to show products by category. Here is my desired output:

[
    {_id: {category: 'cat1'}, {products: [{productName: "ABC"}, {productName: "JKL"}]}},
    {_id: {category: 'cat2'}, {products: [{productName: "DEF"}, {productName: "MNO"}]}},
    {_id: {category: 'cat3'}, {products: [{productName: "GHI"}, {productName: "PQR"}]}}
]

I have written query to group theme by category. Here is the code:

db.products.aggregate([
    {$group: {_id: {category: "$category"}}}
])

How to solve my problem?

CodePudding user response:

Your approach with a $group on $category was good. You just need to use an aggregation operator in the stage.

With $push, you can create a list of products

[
  {
    $group: {
      _id: "$category",
      products: {
        $push: {
          "productName": "$productName"
        }
      }
    }
  }
]

try it here

  • Related