Home > Blockchain >  Unable to sort documents after grouping mongodb aggregation framework
Unable to sort documents after grouping mongodb aggregation framework

Time:05-25

so i am trying to sort notifications array of user by it's insertion date (i want the latest one on top) but it seems to be not working am i missing something ?

here's the template for data:

{
  _id: "628ceeae3df06d49419f0bb4",
  name: "John",
  notifications: [
    {_id: "someIdA", details: "xyz", dateTime: "1653321337762"},
    {_id: "someIdB", details: "jkl", dateTime: "1653321337762"}
    {_id: "someIdC", details: "abc", dateTime: "1653321321323"}
    {_id: "someIdD", details: "lmn", dateTime: "1653123412341"}
  ]
}

and the aggregation pipeline that i'm trying:

const foundUser = await users.aggregate([
    {
      $match: {
        _id: mongoose.Types.ObjectId(userId)
      }
    },
    {
      $project: {
        notifications: 1,
        _id: 0
      }
    },
    {
      $sort: {
        _id: -1
      }
    }
  ])

CodePudding user response:

First unwind the array of notifications array, sort the documents by notifications DateTime key, then group them by the user.

This is the mongo shell query:

  db.collection.aggregate([
  {
    $match: {
      _id: "628ceeae3df06d49419f0bb4"
    }
  },
  {
    $unwind: "$notifications"
  },
  {
    $sort: {
      "notifications.dateTime": -1
    }
  },
  {
    $group: {
      _id: "$_id",
      notifications: {
        $push: "$notifications"
      }
    }
  },
  {
    "$project": {
      "notifications": 1,
      "_id": 0
    }
  }
])

Here, is the working link Mongodb Playground

  • Related