How I can sort data by time? data inside a array and object has a inner array where every object has created value

Issue

Datas are inside an array and each object in that array has an inner array where every object has createdAt value.

So, my intention is to sort them by createdAt.

In this data I want to sort data transactions inside value createdAt.

{
  _id: new ObjectId("62f4ba7fb45d837c4872a577"),
  balance: 13700,
  createdAt: 2022-08-11T08:14:34.086Z,
  transactions: [
    {
      cash: 10000,
      due: 1600,
      total: 11600,
      balance: 1600,
      type: 'order',
      createdAt: 2022-08-11T15:41:30.729Z,
      _id: new ObjectId("62f4cf0190260cd6310f73b7")
    },
    {
      cash: 20000,
      due: 5000,
      total: 25000,
      balance: 6600,
      type: 'order',
      createdAt: 2022-08-11T15:41:30.729Z,
      _id: new ObjectId("62f4cf5190260cd6310f73c4")
    },
    {
      cash: 200,
      due: 0,
      total: 0,
      balance: 6400,
      type: 'add-cash',
      createdAt: 2022-08-11T16:38:09.561Z,
      _id: new ObjectId("62f4dc2c084c7031e0edc770")
    },
    {
      cash: 200,
      due: 0,
      balance: 13700,
      type: 'order',
      createdAt: 2022-08-11T10:49:18.390Z,
      _id: new ObjectId("62f4df966a3f83c597e20e42")
    }
  ],
  __v: 0
}

I tried this but this is a wrong way -_-
const account = await Account.findOne({ userId: userId }).sort({ transactions.createdAt: -1 });

Solution

Try with mongo aggregation like:-

collection.aggregate([
    { $unwind: '$transactions' },
    {
    $sort : { 'transactions.createdAt': -1}
   }, 
   {
    $group: {
        _id: '$_id',
        balance: {$first: '$balance'},
        createdAt: {$first: '$createdAt'},
        transactions: {$push: '$transactions'}
     }
   }
  ]);

it should work for you.

Answered By – krishn kumar modanval

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published