How do I upload several JSON documents to my collection at once?

I have close to 10000 JSON documents, all of which I want to upload in a collection in a db in MongoDB Atlas. I want each JSON document that is on my machine, also show up as a separate document in MongoDB as well. I can upload them one by one through the Compass’ GUI, and it works that way, but surely there must be some quicker way to upload all of them at once?

Hi @Suporno_Sarkar ,

Sure. Try to use mongoimport utility and provide it the json file with all the documents.

https://docs.mongodb.com/database-tools/mongoimport/#:~:text=The%20mongoimport%20tool%20imports%20content,corresponding%20structured%20data%20export%20capability.

You can either script the batch insert into insertMany commands (possible with the new shell as well).

Thanks
Pavel

Hey @Pavel_Duchovny,
Thanks a lot for answering! I could not carry out your advice as I am facing some problems. I am writing that below here.

  1. The mongoimport command looks like 'mongoimport '. I was able to connect to my Cluster but not able to connect to my preferred collection. How do I do that after entering my connection URL.
  2. The above command only accepts a file, but I want to upload several JSON files which are in a single folder, is there some process in the middle that I have to do? Please help.

I also tried the other method you gave. I was able to connect to my db this time as well, but can’t understand where I would write the code for insertMany. It is probably a trivial question, but I don’t understand - do I need to write the code in the shell or in a JS file or something and execute that or what? Also for insertMany I need to give proper file locations for each file, how would I do that? Because when I normally do file-related operations from the terminal, I just cd into it but here, I am connected with my Atlas cluster.

I have so many questions, I apologize, but I am clueless. I am not very experienced in MongoDB, so a guide/walkthrough or even a complete example code would have been nice.

@Suporno_Sarkar ,

You need to add a --collection flag with the collection name to the command. You can specify multiple files with --file flag. You can just script or prepare x commands as much files you have …

See examples :

Thanks
Pavel

1 Like

Hello,

I would like to know if it is possible to mongoimport multiple documents with only on json file?

Or do we need to have one json file per document?

Dói you have an example of a json file with multiple documents defined in it?

If not possible with mongoimport, what else can I use?

Thank you