MongoDB differences between NumberLong and simple Integer?

后端 未结 2 1116
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 10:46

What are the main differences (size, speed, etc) between the datatypes double, NumberLong, NumberInt or a simple Integer in MongoDB?

If I want to save a small fixed

相关标签:
2条回答
  • 2020-12-03 11:27

    NumberLong and NumberInt are not data types in MongoDB but JavaScript functions in the MongoDB shell.

    Data types in MongoDB are defined in the BSON specification: http://bsonspec.org/spec.html

    Numbers are stored as type 0x01 (floating point), type 0x10 (32-bit integer) or type 0x12 (64-bit integer).

    If you insert or update a document in the MongoDB shell, then NumberLong creates a 64-bit integer, NumberInt creates a 32-bit integer, and a regular JavaScript number creates a floating-point value. This is because there are no integers in JavaScript, only floating-point numbers.

    Output in the MongoDB shell shows floating-point numbers and 32-bit integers as JavaScript numbers, whereas 64-bit integers are shown as calls to NumberLong:

    > db.inttest.insert({f: 1234, i: NumberInt("1234"), l: NumberLong("1234")})
    > db.inttest.findOne()
    {
            "_id" : ObjectId("5396fc0db8e0b3e2dedb59b0"),
            "f" : 1234,
            "i" : 1234,
            "l" : NumberLong(1234)
    }
    

    Different MongoDB drivers provide different methods of inserting different types of numbers. For example, the C++ driver creates a 64-bit integer if you append a long long value to a BSONObjectBuilder.

    Queries match whenever the numbers are equal. In the above example, the queries

    > db.inttest.find({i:1234})
    > db.inttest.find({l:1234})
    > db.inttest.find({f:1234})
    > db.inttest.find({i:NumberLong("1234")})
    > db.inttest.find({l:NumberLong("1234")})
    > db.inttest.find({f:NumberLong("1234")})
    

    all match the inserted document.

    0 讨论(0)
  • 2020-12-03 11:42

    NumberInt

    By default, the mongo shell treats all numbers as floating-point values. The mongo shell provides the NumberInt() constructor to explicitly specify 32-bit integers.

    NumberLong

    By default, the mongo shell treats all numbers as floating-point values. The mongo shell provides the NumberLong() class to handle 64-bit integers.

    The NumberLong() constructor accepts the long as a string:

    NumberLong("2090845886852")
    

    Source: http://docs.mongodb.org/manual/core/shell-types/

    0 讨论(0)
提交回复
热议问题