如何显示分类在 MongoDB 中的产品?

How to show products categorized in MongoDB?

我有一个 MongoDB 集合名称为 'products',其中包含这些文档:

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

我想按类别显示产品。这是我想要的输出:

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

我已经编写了按类别对主题进行分组的查询。这是代码:

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

如何解决我的问题?

您在 $category 上使用 $group 的方法很好。 你只需要在舞台上使用aggregation operator

使用 $push,您可以创建 products

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

试一试here