title: Sorting and grouping nested subdocument in Mongoose
body: <p>I have a schema, <code>Comment</code>, like the one below. It's a system of "comments" and "replies", but each comment and reply has multiple versions. When a user wants to view a comment, I want to return just the most recent version with the <code>status</code> of <code>APPROVED</code>.</p>
  
  <pre><code>const Version = new mongoose.Schema({
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
    },
    body: String,
    created: Date,
    title: String,
    status: {
      type: String,
      enum: [ 'APPROVED', 'OPEN', 'CLOSED' ]
    }
  })
  
  const Reply = new mongoose.Schema({
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
    },
    created: Date,
    versions: [ Version ]
  })
  
  const Comment = new mongoose.Schema({
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
    },
    created: Date,
    versions: [ Version ],
    replies: [ Reply ]
  })
  </code></pre>
  
  <p>I've gotten the parent <code>Comment</code> to display how I want with the code below. However, I've had trouble applying that to the sub-document, <code>Reply</code>.</p>
  
  <pre><code>const requestedComment = yield Comment.aggregate([
    { $match: {
      query
    } },
    { $project: {
      user: 1,
      replies: 1,
      versions: {
        $filter: {
          input: '$versions',
          as: 'version',
          cond: { $eq: [ '$$version.status', 'APPROVED' ] }
        }
      },
    }},
    { "$unwind": "$versions" },
    { $sort: { 'versions.created': -1 } },
    { $group: {
      _id: '$_id',
      body: { $first: '$versions.body' },
      title: { $first: '$versions.title' },
      replies: { $first: '$replies' }
    }}
  ])
  .exec()
  </code></pre>
  
  <p>Any help achieving the same result with the <code>replies</code> subdocuments would be appreciated. I would like to return the most recent <code>APPROVED</code> version of each reply in a form like this:</p>
  
  <pre><code>comment: {
    body: "The comment's body.",
    user: ObjectId(...),
    replies: [
      {
        body: "The reply's body."
        user: ObjectId(...)
      }
    ]
  }
  </code></pre>