Dinesh Sathrasala
Dinesh Sathrasala

Reputation: 103

Unable to sort grouped data on aggregation with mongodb

I am grouping leads data based on email and phone combination. And after getting the resultant data when I perform sorting data is not sorted either in ascending or descending order but it is sorting randomly. I am using node js and mongodb(mongoose) for achieving this.

I have swapped the positions of $sort operator and even then wrongly sorted results came.

return db.model('Lead').aggregate([
      {
        $facet: {
          totalData: [
            { $match: queryObj },
            { $group: { _id: { email: "$email", phone: "$phone" }, count: { $sum: 1 }, leads: { $push: { _id: "$_id", name: "$name", firstName: "$firstName", lastName: "$lastName", email: "$email", project: "$project", list: "$list", assignee: "$assignee", phoneCode: "$phoneCode", phone: "$phone", createdAt: "$createdAt", updatedAt: "$updatedAt", utmSource: "$utmSource", source: "$source", unreadmembers: "$unreadmembers" } } } },
            { $sort: {updatedAt: -1} },
            { $skip: (page - 1) * count },
            { $limit: count }
          ],
          totalCount: [
            { $match: queryObj },
            { $group: { _id: { email: "$email", phone: "$phone" } } },
            { $count: "leadsCount" }
          ]
        }
      }
    ]).collation({ locale: "en" }).allowDiskUse(true).exec((err, leadsData) => {
      if (err) {
        console.log("Error: ", err);
      } else {
        console.log("Data: ", leadsData);
      }
    })

I want data to be sorted by updatedAt field. Please help me in fixing this.

Upvotes: 0

Views: 332

Answers (1)

PrasathBV
PrasathBV

Reputation: 323

  1. In $facet use the limit and skip on top order of aggregation pipeline it will improve the performance of execution.

  2. Sort the updatedAt after grouping.

    { $match: queryObj },
    { $skip: (page - 1) * count },
    { $limit: count }
    { $group: { _id: { email: "$email", phone: "$phone" }, count: { $sum: 1 }, leads: 
       { $push: { _id: "$_id", name: "$name", firstName: "$firstName", lastName: 
       "$lastName", email: "$email", project: "$project", list: "$list", assignee: 
       "$assignee", phoneCode: "$phoneCode", phone: "$phone", createdAt: 
       "$createdAt", updatedAt: "$updatedAt", utmSource: "$utmSource", source: 
        "$source", unreadmembers: "$unreadmembers" } } } 
    },
    

    { $sort: { "leads.updatedAt": -1 } }

Upvotes: 1

Related Questions