Mongodb在插入文档时替换键名中的点(.)

use*_*440 6 ruby mongodb

MongoDb不支持带点的键.我有一个Ruby嵌套哈希,它有许多带点(.)字符的键.在将此类数据插入MongoDb时,是否存在可用于指定.类似下划线的字符替换的_配置

我正在使用带Ruby和mongogem的MongoDB .

示例哈希如下所示

{
  "key.1" => {
             "second.key" => {
                             "third.key" => "val"
                           }
             }
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*nil 2

如果无法.在 Mongodb 中使用键,则必须修改输入数据:

hash = {
  'key.1' => {
    'second.key' => {
      'third.key' => 'val.1',
      'fourth.key' => ['val.1', 'val.2']
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

转换字符串键

此递归方法转换嵌套 Hash 的键:

def nested_gsub(object, pattern = '.', replace = '_')
  if object.is_a? Hash
    object.map do |k, v|
      [k.to_s.gsub(pattern, replace), nested_gsub(v, pattern, replace)]
    end.to_h
  else
    object
  end
end
Run Code Online (Sandbox Code Playgroud)

nested_gsub(hash)返回:

{
    "key_1" => {
        "second_key" => {
             "third_key" => "val.1",
            "fourth_key" => [
                "val.1",
                "val.2"
            ]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

转换键和值

可以在之前的方法中添加更多案例:

def nested_gsub(object, pattern = '.', replace = '_')
  case object
  when Hash
    object.map do |k, v|
      [k.to_s.gsub(pattern, replace), nested_gsub(v, pattern, replace)]
    end.to_h
  when Array
    object.map { |v| nested_gsub(v, pattern, replace) }
  when String
    object.gsub(pattern, replace)
  else
    object
  end
end
Run Code Online (Sandbox Code Playgroud)

nested_gsub现在将迭代字符串值和数组:

{
    "key_1" => {
        "second_key" => {
             "third_key" => "val_1",
            "fourth_key" => [
                "val_1",
                "val_2"
            ]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)