skip to Main Content

Can I update a field of a document with a division of two fields? Using Node and MongoDB, I’m trying to create a rating function, and I have to make a division, but nothing seems to work. I want the new value of rating to be, the current one divided by the number of votes.


router.put("/:id/:rating", async (req, res) => {
    const movie_rating = parseInt(req.params.rating);
    try {
        const updatedMovie = await Movie.findByIdAndUpdate(
            req.params.id,
            {
                $inc: { noVotes: 1 },
                $inc: { rating: movie_rating },
                $divide: { rating: [rating, noVotes] },
                // rating: { $divide: [rating, noVotes] }
            },
            { new: true }
        );
        res.status(200).json(updatedMovie);
    } catch (err) {
        res.status(500).json(err);
    }
});

2

Answers


  1. You need to change few things

    Sample

    db.collection.update({},
    [
      {
        "$set": {
          "key2": {
            $add: [
              "$key2",
              1
            ]
          },
          key3: {
            "$divide": [
              {
                $add: [
                  "$key2",
                  1
                ]
              },
              "$key"
            ]
          },
          
        }
      }
    ],
    {
      "multi": true,
      "upsert": false
    })
    
    1. You need aggregate update as you need divide
    2. You cannot use the updated value in the same operation
    3. You cannot combine $inc, $set in aggregate update
    4. Alternatively, you can use $add instead $inc
    5. you can reperform the operation for the divide operation than making another update call
    Login or Signup to reply.
  2. This can be done with $set,
    It will look like this:

    router.put("/:id/:rating", async (req, res) => {
      const movie_rating = parseInt(req.params.rating);
      try {
        const updatedMovie = await Movie.findByIdAndUpdate(
          req.params.id,
          [
            {
              $set: {
                noVotes: { $sum: ["$noVotes", 1] },
                rating: { $sum: ["$rating", movie_rating] },
                averageRating: { $divide: ["$rating", "$noVotes"] },
              },
            },
          ],
          { new: true }
        );
        res.status(200).json(updatedMovie);
      } catch (err) {
        res.status(500).json(err);
      }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search