Inserting new Documents in a collection

I was going through the Inserting new documents lecture in the Creating and Manipulating Documents chapter inside the MongoDB basics tutorial and a point struck me. It said while inserting new documents in a collection if we do a typo in mentioning the name of the collection or in a similar manner make a mistake in naming the Database, then a new collection/database is created and no error is thrown even though it might have been a case if we used the right/specified collection or database. Wouldn’t this cause an issue while working with large programs.
To be precise what if I was working on a project and wanted to make some entries in a collection but did a typing error and a new collection was made instead which I was not informed of while I still believe I did the right thing, would this not be a big issue?
I am new to MongoDB so wanted to get this out of my mind.
Any help is appreciated.

Hi @Mike_N_A1 welcome to the community!

Yes operations like db.collection.insert() will create the collection if it doesn’t exist. It won’t throw an error, since it’s not really an error, rather that’s how the method was designed to work.

Well technically the database only does what you tell it to, so it’s best to double check for typos in important operations :slight_smile:

However if a new collection was created by accident, you can use the aggregation’s $merge operation to merge the two collections together, then drop the wrong one.

I am new to MongoDB so wanted to get this out of my mind.

Welcome!

Best regards
Kevin

5 Likes

Thank you @kevinadi for the help, I’ll keep those things in mind that you stated. Especially the $merge operation.
Appreciate the help

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.