我正在尝试从 mongodb 获取数据,但没有得到预期的输出

I am trying to get retrive data from mongodb but not getting expected output

数据库数据-

[{
    title: "Vivo X50",
    category: "mobile",
    amount: 35000

},
{
    title: "Samsung M32",
    category: "mobile",
    amount: 18000

},
{
    title: "Lenovo 15E253",
    category: "laptop",
    amount: 85000

},
{
    title: "Dell XPS 15R",
    category: "laptop",
    amount: 115000
}]

预期输出:

[{
    category: "mobile",
    qty: 2,
    totalAmount: 53000
},
{
    category: "laptop",
    qty: 2,
    totalAmount: 200000
}]

代码我是运行(使用mongoose)

let products = await Product.aggregate([
    {
      $project: { _id: 0, category: 1, amount: 1 },
    },
    {
      $group: {
        _id: "$category",
        qty: { $sum: 1 },
        totalAmount: { $sum: "$amount" },
      },
    },
  ]);

我得到的结果。

[
{
"_id": "laptop",
"count": 2,
"totalSum": 200000
},
{
"_id": "mobile",
"count": 2,
"totalSum": 53000
}
]

你可以清楚地看到我能够获得正确的数据,但我想要正确的名称和类别而不是 _id。请帮助我。提前致谢

您需要$project作为最后阶段来修饰输出文档。

{
  $project: {
    _id: 0,
    category: "$_id",
    qty: "$qty",
    totalAmount: "$totalAmount"
  }
}

同时,第一阶段$project不需要。

db.collection.aggregate([
  {
    $group: {
      _id: "$category",
      qty: {
        $sum: 1
      },
      totalAmount: {
        $sum: "$amount"
      }
    }
  },
  {
    $project: {
      _id: 0,
      category: "$_id",
      qty: "$qty",
      totalAmount: "$totalAmount"
    }
  }
])

Sample Mongo Playground

您可以使用以下查询来获得预期的输出。干杯~

await Product.aggregate([
  {
    $group: {
      _id: "$category",
      qty: {
        $sum: 1
      },
      totalAmount: {
        $sum: "$amount"
      },
      
    },
    
  },
  {
    $addFields: {
      category: "$_id"
    }
  },
  {
    $project: {
      _id: 0
    },
    
  }
])