[MongoDB] Query to Get Documents with nth Decimal Places and Update with mth Decimal Place Values

Tadashi Shigeoka ·  Sun, March 12, 2017

As an application of how to get the number of decimal places in JavaScript, I wrote a query in MongoDB to get documents with 3rd decimal places and beyond and update them to 2nd decimal places.

MongoDB | モンゴディービー

var skus = db.skus.find(
  {
    $or: [
      {
        $where: function() {
          var numbers = String(this.price).split('.');
          var result = 0;

          if (numbers[1]) {
            result = numbers[1].length;
          }

          // Check if it has 3rd decimal places or more
          return result > 2;
        }
      },
      {
        $where: function() {
          var numbers = String(this.salePrice).split('.');
          var result = 0;

          if (numbers[1]) {
            result = numbers[1].length;
          }

          return result > 2;
        }
      }
    ]
  }
).toArray();

// Converter to convert to 2nd decimal place values
var converter = function(num) {
  return parseFloat(num.toFixed(2));
};

skus.forEach(function(s){
  if (s.price) {
    s.price = converter(s.price);
  }
  if (s.salePrice) {
    s.salePrice = converter(s.salePrice);
  }

  // printjsononeline(s);

  var ret = db.skus.save(s);
  printjsononeline(ret);
  print('');
});

The key point is the $where: function() { } part that determines whether price or salePrice has 3rd decimal places or more.

Using the $where operator, you can often achieve complex conditional queries by leveraging JavaScript programming, so please try using $where.

That’s all from the Gemba.