How do merge those with the same k values?

const topChatStatisticChannels = await Bot.Models.Stats.aggregate([
        {
          $match: {
            userId: userId,
            date: {
              $gte: startDate,
              $lte: endDate,
            },
          },
        },
        {
          $group: {
            _id: "$userId",
            topChatChannels: { $push: { $objectToArray: "$chat" } },
          },
        },
        {
          $unwind: {
            path: "$topChatChannels",
          },
        },
        {
          $unwind: {
            path: "$topChatChannels",
          },
        },

        {
          $sort: {
            "topChatChannels.v": -1,
          },
        },
        {
          $group: {
            _id: "$userId",
            topChatChannels: {
              $push: "$topChatChannels",
            },
          },
        },
      ]).exec();

Now output:
[
{ k: ‘1017511111488188477’, v: 141 },
{ k: ‘1017511111488188477’, v: 110 },
{ k: ‘1017511239389302925’, v: 3 },
{ k: ‘987298045832073236’, v: 2 }
]

In the aggregate code above, it gives me the output now, but I want to aggregate the k values and return them, how can I do it. I specified the output I want below.

Wanted output:
[
{ k: ‘1017511111488188477’, v: 251 },
{ k: ‘1017511239389302925’, v: 3 },
{ k: ‘987298045832073236’, v: 2 }
]

Your last stage is a $group but your output does not have an _id. So I suspect that your output is a little bit more than what you shared. Could you share the complete output of what you get?

I’m sorry, I didn’t realize. Here it is:
[
{
_id: null,
topChatChannels: [ [Object], [Object], [Object], [Object] ]
}
]

You first $unwind topChatChannels.

Then you $group with

A final $project to k rather than _id with

2 Likes

It’s done, thank you so much.

1 Like