5

We have an application that stores some configuration values from C/C++ in MongoDB and has the capability to be restarted (i.e. it runs for a while, someone interrupts the application, changes the configuration, then runs the app again, and it picks up where it left off). This works like a charm for boolean and string configurations.

But then we have some integers (in our current C/C++ implementation - 32 bit values). And when I use the MongoDB console to modify those integer values, Mongo always stores them back as Number (which is doulble in the C/C++ implementation). We will change the app to take double values where it expects integers but I was wondering if there is a way to force Mongo to store integers from its JavaScript console.

Any suggestions?

3 Answers3

9

In the C/C++ "sense of the word", ints are not actually guaranteed to be 32-bit values. An int must be at least 16-bits, but generally matches the platform architecture (eg. 32 or 64bit).

As mentioned by @Jasd, JavaScript does only have one numeric type which is a floating point (double in C).

From the MongoDB shell you should be able to use the functions NumberInt(..) to get a BSON 32-bit integer value or NumberLong(..) to get a BSON 64-bit integer.

Community
  • 1
  • 1
Stennie
  • 63,885
  • 14
  • 149
  • 175
9

You can fix the types of all values for a certain field on the console with something like:

db.Statistic.find({kodoId: {$exists: true}}).forEach(function (x) {
  x.kodoId = NumberInt(x.kodoId);
  db.Statistic.save(x);
});

This will only load documents that have the kodoId field and convert them to int and resave. You could do something like:

db.Statistic.find({kodoId: {$exists: true}}, {kodoId: 1}).forEach(function (x) {
   db.Statistic.update({ _id: x._id },
      {$set: {
        kodoId: NumberInt(x.kodoId)
      }});
});

with a second param which will only load the kodoId value (hopefully from an index). This should be much quicker since it doesn't need to load and resave the entire document - just that one field.

Nic Cottrell
  • 9,401
  • 7
  • 53
  • 76
0

MongoDB's shell is powered by a JavaScript Engine. And JavaScript has no type for integer. It knows only Number, which is a type for floating-point numbers.
You can try using the MongoDB type NumberLong, but it didn't work out for me when i once had the same problem.

Johannes Egger
  • 3,874
  • 27
  • 36