How to query and sort Mongoose subdocuments

Viewed 83

I need to get the card inside of deck which has the lowest stats.reviewDate value.

For example, a query on this:

{
    "_id": "608642db80a36336946620aa",
    "cards": [
        {
            "stats": {
                "reviewDate": "1985-03-26T04:34:17.425Z",
            },
            "_id": "6086430080a36336946620ab",
            "front": "front",
            "back": "back"
        },
        {
            "stats": {
                "reviewDate": "2021-05-26T04:34:17.425Z",
            },
            "_id": "6086430080a36336946620ab",
            "front": "front",
            "back": "back"
        },
        {
            "stats": {
                "reviewDate": "2021-04-26T04:34:17.425Z",
            },
            "_id": "6086430080a36336946620ab",
            "front": "front",
            "back": "back"
        }
    ]
}

should return:

       {
            "stats": {
                "reviewDate": "1985-03-26T04:34:17.425Z",
            },
            "_id": "6086430080a36336946620ab",
            "front": "front",
            "back": "back"
        }

I've tried to achieve this by sorting the cards in descending order, and reading the first item in the list:

 DeckModel.findById(req.params.deckId, 'cards')
  .sort({'cards.stats.dateCreated': 'desc'})
  .exec((err, docs) => {
    if(err) { return next(err) }
    console.log(docs.cards.[0]);
  });

But it doesn't work - certainly due to my poor understanding of .sort())

Here is a similar question to mine, although it has no accepted answer.

How would one construct a query that returns my desired result?

Here are my schemas, if needed:

    var DeckSchema = new Schema ( 
      {
        title: { type: String, required: true, maxlength: 255 },
        cards: [CardSchema]
      }
    )
    var CardSchema = new Schema(
      {
        stats: {
          reviewDate: {type: Date, default: Date.now(), required: true},
        },
        front: String,
        back: String
      }
    )

Thanks all,

  • Sour_Tooth
1 Answers

Demo - https://mongoplayground.net/p/RUssJuB7XO2

db.collection.aggregate([
  // { $match: {  } }, your query here
  { $unwind: "$cards" },
  { $sort: { "cards.stats.dateCreated": -1 } },
  { $limit: 1 },
  { $replaceRoot: { "newRoot": "$cards" } }
])
Related