mongoose 在MongoDB中获取每个类别的最新对象

new9mtju  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(121)

我有一个这样的系列

{
  category: "Groceries",
  items: [...],
  price: 30.0,
  purchased: "04-10-2022 17:52:35"
},
{
  category: "Groceries",
  items: [...],
  price: 11.0,
  purchased: "04-10-2022 18:52:35"
},
{
  category: "Cleaners",
  items: [...],
  price: 10.0,
  purchased: "04-10-2022 17:52:35"
},

我想通过一个查询获取每个category的最近购买情况。
结果应该是:

{
  category: "Groceries",
  items: [...],
  price: 11.0,
  purchased: "04-10-2022 18:52:35"
},
{
  category: "Cleaners",
  items: [...],
  price: 10.0,
  purchased: "04-10-2022 17:52:35"
},
btxsgosb

btxsgosb1#

  • 首先,您需要使用排序来排序所有记录购买的财产
  • 第二组按类别,只推送第一个项目。
  • 替换root以获取主记录主体。
[
  // sort the dates to get the latest first
  {$sort: {purchased: -1}},
  // group to get the most recent purchased record per category
  {$group: {_id: '$category', record: {$first: '$$ROOT'}}},
  // replace root to get the main record body
  {$replaceRoot: {newRoot: '$record'}},
]

相关问题