@@ -173,16 +173,17 @@ def multi_workers_ready?
173173
174174 def write ( chunk )
175175 collection_name = extract_placeholders ( @collection , chunk . metadata )
176- operate ( format_collection_name ( collection_name ) , collect_records ( chunk ) )
176+ database_name = extract_placeholders ( @database , chunk . metadata )
177+ operate ( database_name , format_collection_name ( collection_name ) , collect_records ( chunk ) )
177178 end
178179
179180 private
180181
181- def client
182+ def client ( database = @database )
182183 if @connection_string
183184 Mongo ::Client . new ( @connection_string )
184185 else
185- @client_options [ :database ] = @ database
186+ @client_options [ :database ] = database
186187 @client_options [ :user ] = @user if @user
187188 @client_options [ :password ] = @password if @password
188189 Mongo ::Client . new ( @nodes , @client_options )
@@ -227,7 +228,8 @@ def collection_exists?(name)
227228 end
228229 end
229230
230- def get_collection ( name , options )
231+ def get_collection ( database , name , options )
232+ @client = client ( database ) if database && @database != database
231233 return @client [ name ] if @collections [ name ]
232234
233235 unless collection_exists? ( name )
@@ -242,7 +244,7 @@ def forget_collection(name)
242244 @collections . delete ( name )
243245 end
244246
245- def operate ( collection , records )
247+ def operate ( database , collection , records )
246248 begin
247249 if @replace_dot_in_key_with
248250 records . map! do |r |
@@ -255,7 +257,7 @@ def operate(collection, records)
255257 end
256258 end
257259
258- get_collection ( collection , @collection_options ) . insert_many ( records )
260+ get_collection ( database , collection , @collection_options ) . insert_many ( records )
259261 rescue Mongo ::Error ::BulkWriteError => e
260262 log . warn "#{ records . size - e . result [ "n_inserted" ] } documents are not inserted. Maybe these documents are invalid as a BSON."
261263 forget_collection ( collection )
0 commit comments