【问题标题】:Configure Mongo shell to store all numbers as integers by default配置 Mongo shell 以默认将所有数字存储为整数
【发布时间】:2014-06-06 15:33:48
【问题描述】:

默认情况下,MongoDB shell 将所有数字解释为浮点数;当试图将现有的 JSON 格式数据(在 Mongo 中存储为字符串)转换为实际的 Mongo BSON 对象时,这是一个问题。使用NumberInt(...)/NumberLong(...) 显式手动包装数据中的任何整数值也很繁琐,因为整数可以出现在数据中的任何位置。

有没有办法将一个 MongoDB shell 会话配置为默认使用 NumberInt 或 NumberLong?

或者:有没有办法将 JSON 字符串解析为 MongoDB shell 中的对象,以便所有不带小数点的数字都已经用 NumberInt/NumberLong 包裹? p>

【问题讨论】:

    标签: mongodb mongodb-shell


    【解决方案1】:

    我现在最终使用的解决方案是对从JSON.parse 返回的数据调用markIntegers 函数;它似乎工作正常。为了完整起见,我将其发布在这里;非常欢迎更好的解决方案和更正!

    function markIntegers(obj) {
        if (obj instanceof Array) {
            return obj.map(function(x) { return markIntegers(x); });
        // make sure it's a plain object and not Date or BinData etc
        } if (obj !== null && typeof obj === "object" && obj.constructor === Object) {
            var ret = {}
            for (var key in obj)
                ret[key] = markIntegers(obj[key]);
            return ret;
        } else if (typeof obj === "number") {
            return obj === Math.floor(obj) ? NumberLong(obj) : obj;
        } else {
            return obj;
        }
    }
    

    它的工作原理是这样的:

    > markIntegers({a: {b: 3}, c: 4.4, e: ["hello"]})
    { "a" : { "b" : NumberLong(3) }, "c" : 4.4, "e" : [ "hello" ] }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-27
      • 2016-05-29
      • 2012-07-05
      • 1970-01-01
      相关资源
      最近更新 更多