Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
How can I find MONGODB documents based on random numbers(based on length of documents) and choose specific fields from documents(Raffle draw winners)

I want to select raffle draw winners so for that based on certain conditions I've chosen the documents from Mongodb from which winners are to be chosen. Next, I need to generate random numbers based on the number of winners(Number of winners is taken from client side - React) and find the winners. But I also have to save the winners to the Mongodb database. I could do it for one winner but if the number of winner is more than one, how can I do this?

 const chooseWinner = await Transaction.find(
    {
      ContCode: CountryCode,
      CurrCode: CurrCode,
      CorrOrgCode: CorrorgCode,
      ServCode: ServCode,
      BranchCode: BranchCode,
      Trandate: {
        $gte: FromDate,
        $lte: ToDate,
      },
    },
    "CustomerCode ReferenceNo Trandate NoOfWinners"
  );

  //to get no of docs

  const docLength = Object.keys(chooseWinner).length;
   console.log("length: ",docLength);
   console.log(JSON.stringify(chooseWinner));
    if(docLength == 0)
    {
      console.log("No winner");
      res.status(400).send({ message: "winner not found" });
    } else {
   //to choose random winner
   var random1 = Math.floor(Math.random() * docLength);
   console.log("random no: ",random1);
    
    try {
    //adding raffle draw winner details to db
    const updateRaffledraw = await Raffledraw.findOneAndUpdate(
      {RaffleCategory : req.params.category},
      {$set: 
        { winners: {
            CustomerCode: chooseWinner[random1].CustomerCode,
            ReferenceNo: chooseWinner[random1].ReferenceNo
      },
    }
  },
      {multi : true}
    );
    
  } catch (err) {
    res.status(400).send(err);
  } 
}
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!