Mongodb replaces dot (.) In key name when inserting document

MongoDb does not support dotted keys. I have a hash nested Ruby that has many keys with a symbol (.). Is there a configuration that can be used to specify a character replacement for ., such as underscore _, inserting such data into MongoDb

I am using MongoDB with Ruby and mongogem.

An example hash looks below

{
  "key.1" => {
             "second.key" => {
                             "third.key" => "val"
                           }
             }
}
+6
source share
2 answers

If it is not possible to use the c keys in Mongodb ., you will have to change the input:

hash = {
  'key.1' => {
    'second.key' => {
      'third.key' => 'val.1',
      'fourth.key' => ['val.1', 'val.2']
    }
  }
}

String key conversion

This recursive method converts the keys of a nested 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

nested_gsub(hash) returns:

{
    "key_1" => {
        "second_key" => {
             "third_key" => "val.1",
            "fourth_key" => [
                "val.1",
                "val.2"
            ]
        }
    }
}

Key and Value Conversion

:

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

nested_gsub :

{
    "key_1" => {
        "second_key" => {
             "third_key" => "val_1",
            "fourth_key" => [
                "val_1",
                "val_2"
            ]
        }
    }
}
+2

mongoDB . ​​ MongoDB JSON.

, U + FF0E.

, .

0

Source: https://habr.com/ru/post/1013868/


All Articles