Will insertOne create collection and new document in it?

Hi All,

While doing hands-on on InsertOne, I did following:
use video
db.moviesScratch.insertOne(…)

It should have created new collection for me with name as moviesScratch and insert a document into it. but neither I got any error nor new collection was created. Where this document is inserted?
For more details, please see attached screenshot wherein I have highlighted DB, collections and documents.
Insert_noerror

you can check if the documents were inserted by either finding them by id or pull all the documents up. You can look up all the documents by doing this to verify:

db.movieScratch.find().pretty()

also the shell is stating that the document was created and displays the ObjectId

1 Like

Hi Shahid,

My query is for moviesScratch collection and not movieScratch.

Thanks,
Harish

So, what does “show collections” show you? Did it create the new collection? :slight_smile: Your screenshot doesn’t show a shocolls after your typo.

But yes, MongoDB does silently and automatically create a new collection if you insert something into a non-existent collection.

41

Q.E.D.

No it did not create the collection. My understanding was that it should create collection.

Thanks,

Harish

It should, yes… as it did in my case. So something else must’ve happened. Very odd.

Hi Harish_20733,

The MAIN point is:

MongoDB will create a collection if you run insertOne and if it does not exist before.

But it is not true reversibly, if you are looking at show collections before doing an insertOne , then it won’t be showing the collection. You have to check after you have performed an insert operation.

Lets take a look step-wise:

The steps you have taken and my understanding is:

  • You have run show collections which does not show moviesScratch.
    ** You may have not run insertOne on moviesScratch yet.
  • You are running db.moviesScratch.insertOne , and it shows acknowledged: True
    ** It means the collection must have been created and the document should be inserted there.
  • You are running db.movieScratch.insertOne, it also shows acknowledged: True.
    ** It means you got one document inserted in movieScratch.

–To DO:

  • Run show collections under video database now, it will be showing moviesScratch:

    use video
    show collections
    db.moviesScratch.find()
    

Let me know if it is still not clear!

Kanika