Search code examples
node.jsmongodbmongoose

Mongoose Filter & Sort Array of Objects Using Aggregate


i'm new in Nodejs and Mongodb. I have schema like this:

var x= new Schema({
        title: string,
        articles: [{
            article_date: Date    
            seq: Number
        }]
    }),
Book = mongoose.model('Book', orderSchema);

I have data like this:

{
  title: "a",
  articles: [
    {article_dt: "2023-05-09T00:00:00.000+00:00", seq:1},
    {article_dt: "2021-12-31T00:00:00.000+00:00", seq:2},
    {article_dt: "2022-12-31T00:00:00.000+00:00", seq:3}
  ]
}

I want to show the data based on parameter article_date and sort article_date desc.

I've tried this and i can filter the data based on parameter

let paramDate: Date
Book.aggregate([{
    $project:{
        articles:{
            $filter:{
                input: '$articles',
                    as: 'art',
                        cond: {$lt: ['$$art.article_dt', paramDate]}
            }
        }
    }
}])

But i dont know how to sort the array. I want to sort desc. I've tried this https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortArray/ but it wont work..

I'm using: Mongoose 6.11.1 Node 16.16.0 Mongodb 5.0.9

Please help


Solution

  • db.collection.aggregate([
      {
        $project: {
          articles: {
            $filter: {
              input: "$articles",
              as: "art",
              cond: {
                $lt: [
                  "$$art.article_dt",
                  "2023-01-01T00:00:00.000+00:00"
                ]
              }
            }
          }
        }
      },
      {
        "$unwind": "$articles"
      },
      {
        "$sort": {
          "articles.article_dt": 1
        }
      },
      {
        "$group": {
          "_id": "$_id",
          "articles": {
            "$push": {
              article_dt: "$articles.article_dt",
              seq: "$articles.seq"
            }
          }
        }
      }
    ])
    

    mongoplayground