分组并获取最大值 MongoDb

Group by and Get Max Value MongoDb

我想获得每个 numId 的最高计数并将其显示在我的前端 table。

这是我的数据库的示例:

{
  "_id": {
    "$oid": "6294777f677b4c647e28771a"
  },
  "numId": "5",
  "respondee": "0x9d95bcaa5b609fa97a7ec860bec115aa94f85ba9",
  "__v": 0,
  "originalResponse": "test2",
  "submittedAt": {
    "$date": {
      "$numberLong": "1653897087357"
    }
  },
  "addresses": [
    "0x39c878a3df98002ddba477a7aa0609fb5a27e2ff",
    "0xe3342d6522ad72f65d6b23f19b17e3fb12161f90"
  ],
  "count": 2
},
{
  "_id": {
    "$oid": "6294836e677b4c647e287e93"
  },
  "numId": "5",
  "respondee": "0xe3342d6522ad72f65d6b23f19b17e3fb12161f90",
  "__v": 0,
  "originalResponse": "test3",
  "submittedAt": {
    "$date": {
      "$numberLong": "1653900142375"
    }
  },
  "addresses": [
    
  ],
  "count": 0
}

我写过类似的东西,但我不确定如何根据 numId

对结果进行分组
import Response from '../../../models/Response.model';
import db from '../../../utils/config/db';
import nc from 'next-connect';
import { onError } from '../../../utils/error';

const handler = nc({
  onError,
});

//GET all 
handler.get(async (req, res) => {
  await db.connect();

  let responses = await Response.find({ });
  //To group responses by numId

    // Sort responses by votes in ascending order
    responses = responses.sort((a, b) => {
      return a.count - b.count;
    });

    let topResponses = responses.filter((response) => {
      return response.count === responses[0].count;
    });

    // Check if respondee has the highest count response
    if (
      topResponses.length > 0 &&
      topResponses.find((response) => {
        return response.respondee === respondee;
      })
    ) {
      // Get the response
      let response = topResponses.find((response) => {
        return response.respondee === respondee;
      });
      // Get the response
      let responseString = response.response;

      // Get the count
      let count = response.count;
    }

  await db.disconnect();
});

export default handler;

我参考另一个Whosebug找到了答案:

       let responses = await Response.aggregate([
    { $sort: { votes: -1 } },
    { $group: { _id: '$baseId', group: { $first: '$$ROOT' } } },
    { $replaceRoot: { newRoot: '$group' } },
  ]);

  res.send(responses);