猫鼬组文档按值排列,但每个仅返回最新文档

时间:2020-05-11 15:50:33

标签: node.js mongodb mongoose

我有一个名为“单词”的集合,在其中以不同的语言保存了不同的单词。单词存储在“内容”中,语言代码存储在“ lang”中(en,de,fr)。

这是我的Word架构:

content: { 
  type: String
},
lang: {
  type: String,
  enum: ['en', 'de', 'fr']
}

我现在正在尝试检索每种语言的最新存储值,而每种语言仅返回一个文档。

这是我想要的示例输出:

[{
  lang: "en",
  content: "Whats up"
},{
  lang: "de",
  content: "Guten Tag"
},{
  lang: "fr",
  content: "Salut"
}]

我已经尝试将聚合函数与group一起使用。但是现在,两个字母的语言代码作为文档ID返回:

Words.aggregate([{
  $group: {
    _id: '$lang'
  }
}]

1 个答案:

答案 0 :(得分:1)

Words.aggregate([{$sort: {'_id': -1}}, 
{$group: {_id:'$lang',
  word: {
    $push: {
      _id: '$_id',
      content: '$content'
    }
  }
}}, 
{$project: {
  _id:0,
  lang:'$_id',
  content: {$arrayElemAt:['$word.content',0]}
}}])

首先,我按降序对_id进行了排序。 (假设您使用过mongoDB自动生成的_id)

接下来,按语言对所有内容进行分组,最后根据_id投影最新的第一个内容。