Home > Blockchain >  Group by and Get Max Value MongoDb
Group by and Get Max Value MongoDb

Time:06-02

I would like to get the highest number of counts for each numId and display it on my front end in a table.

Here is an example of my database:

{
  "_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
}

I have written something like this but I'm not sure how to group the results according to the numId

import Response from '../../../models/Response.model';
import db from '../../../utils/config/db';
import nc from 'next-connect';
import { one rror } from '../../../utils/error';

const handler = nc({
  one rror,
});

//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;

CodePudding user response:

I have figured out the answer by referring from another stackoverflow: Group by and Get Max Value MongoDb

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

  res.send(responses);
  • Related