skip to Main Content

I want to store maximum length, breadth, area ever encountered from a request and store it in the database. In this case, anything can be maximum and based on that I want to update max values in the database for that particular field only.

const body = {
  oID: 123, // Primary key
  length: 50,
  breadth: 50
};
const { length, breadth } = body;
const currentArea = length * breadth;
await totalArea.updateOne(
  { oID: 123 },
  {
    $set: { $maxLength: maxLength < length ? length : $maxLength }, // I want to update the docs based on mongo query only since this won't work.
    $set: { $maxBreadth: maxBreadth < breadth ? breadth : $maxBreadth },  // I want to update the docs based on mongo query only since this won't work.
    $set: { $maxArea: maxArea < currentArea ? currentArea : $maxArea }  // I want to update the docs based on mongo query only since this won't work.
  },
  { upsert: true }
);

In the above example, I have demonstrated the logic using ternary operator and I want to perform the same operation using mongoDB query. i.e update a particular field while comparing it to existing fields from the database and update it if it satisfies the condition.

2

Answers


  1. Chosen as BEST ANSWER
    await totalArea.updateOne(
      { oID: 123
          },
          {
            $max: {
              maxLength: length,
              maxBreadth: breadth,
              maxArea : currentArea
            }
          },
          { upsert: true }
        );
    

    I found this to be working correctly. Thanks to @Mehari Mamo's comment.


  2. If I understand correctly, you want something like this:

    db.collection.update({
      oID: 123
    },
    [{$set: {maxLength: {$max: [length, "$maxLength"]},
             maxBreadth: {$max: [breadth, "$maxBreadth"]},
             maxArea : {$max: [currentArea, "$maxArea "]}
          }
        }
    ],
    {
      upsert: true
    })
    

    You can check it here .

    The [] on the second step allows you to access the current values of the document fields, as this is an aggregation pipeline.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search