Stephan K.
Stephan K.

Reputation: 15752

MongoDB: Find numbers according to number of decimal places

Here's a tough one:

I want to find all documents in my collection, that have more than 2 decimals after the floating point, e.g. documents containing the

value: 2.45

..should not be returned, where as documents containing numbers like:

value: 2.0000003

should be returned. It goes without saying that the numbers differ.

Upvotes: 3

Views: 3330

Answers (2)

chridam
chridam

Reputation: 103455

Using a custom function that returns the number of decimal places in a number:

var decimalPlaces = function (num) {
  var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
  if (!match) { return 0; }
  return Math.max(
       0,
       // Number of digits right of decimal point.
       (match[1] ? match[1].length : 0)
       // Adjust for scientific notation.
       - (match[2] ? +match[2] : 0));
}

you can iterate over your collection using the forEach method on the find() cursor, save to another collection those documents which have the field value decimal places greater than 2:

db.collection.find().forEach( function (x) {   
    if decimalPlaces(x.value) > 2
       db.new_collection.save(x);
});

Upvotes: 1

Stephan K.
Stephan K.

Reputation: 15752

I found only this alternative, doing it with JavaScript iterating over the returned JSON data:

decimalPlaces = (num) ->
  match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/)
  if !match
    return 0
  Math.max 0, (if match[1] then match[1].length else 0) - (if match[2] then +match[2] else 0)

if decimalPlaces (myDocument.mySubDocument) > 2
  console.log "got ya!" 

note: above is coffeescript

Upvotes: 1

Related Questions