Leonard Niehaus
Leonard Niehaus

Reputation: 530

Mongoose group documents by value but only return latest document each

I have a collection called "Words", where I save different Words in different languages. Words are stored in "content" and their language code in "lang" (en, de, fr).

This is my Words schema:

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

I am now trying to retrieve the latest stored value for each language, only returning one document each.

This is my desired example output:

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

I've already tried to use aggregate function with group. But now the two letter language code gets returned as the document id:

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

Upvotes: 0

Views: 426

Answers (1)

Koodies
Koodies

Reputation: 550

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

First, I used sort on _id by descending order. (Assuming you had use mongoDB auto-generated _id)

Next, group all the content by language and lastly project the first content which is the latest according to _id.

Upvotes: 2

Related Questions