diff --git a/lib/mongo/operation/shared/idable.rb b/lib/mongo/operation/shared/idable.rb index eaf570b042..82fc3fe5b1 100644 --- a/lib/mongo/operation/shared/idable.rb +++ b/lib/mongo/operation/shared/idable.rb @@ -58,7 +58,13 @@ def has_id?(doc) def ensure_ids(documents) @ids = [] documents.collect do |doc| - doc_with_id = has_id?(doc) ? doc : doc.merge(_id: id_generator.generate) + doc_with_id = if has_id?(doc) + doc + else + doc.delete('_id') + doc.merge(_id: id_generator.generate) + end + @ids << id(doc_with_id) doc_with_id end diff --git a/spec/mongo/operation/insert_spec.rb b/spec/mongo/operation/insert_spec.rb index 2c15d0fef6..3393c5211c 100644 --- a/spec/mongo/operation/insert_spec.rb +++ b/spec/mongo/operation/insert_spec.rb @@ -100,6 +100,25 @@ expect(inserted_ids).to eq(collection_ids) end end + + context 'when document contains a nil id' do + + let(:documents) do + [{ 'field' => 'test', '_id' => nil }] + end + + let(:inserted_ids) do + insert.execute(authorized_primary, context: context).inserted_ids + end + + let(:collection_ids) do + authorized_collection.find(field: 'test').collect { |d| d['_id'] } + end + + it 'adds an id to the documents' do + expect(inserted_ids).to eq(collection_ids) + end + end end describe '#execute' do