skip to Main Content

I have a MongoDB Collection with objects of type:

{
  id: 1223
  items: [{
    length: 12.233333,
  }, {
    length: 4.2323232323232,
  }]
}

How can I update the length of each item by rounding to 2 decimals.

2

Answers


  1. You can use $round operator like this:

    db.collection.update({},
    [
      {
        "$set": {
          "items": {
            $map: {
              input: "$items",
              as: "item",
              in: {
                length: {
                  $round: [
                    "$$item.length",
                    2
                  ]
                }
              }
            }
          }
        }
      }
    ])
    

    Playground link.

    Login or Signup to reply.
  2. Try this one:

    db.collection.aggregate([
       {
          $set: {
             items: {
                $map: {
                   input: "$items",
                   in: { length: { $round: ["$$this.length", 2] } }
                }
             }
          }
       }
    ]);
    

    Mongo Playground

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