Import more than 1 json file using mongoimport

前端 未结 12 1398
猫巷女王i
猫巷女王i 2020-11-30 00:27

I am new to mongodb and want to know about importing a json file from one server to another. I tried the following command mongoimport -d tes

相关标签:
12条回答
  • 2020-11-30 00:29

    You can do it by this way also :

    for filename in *; do mongoimport --db <Database> --collection <Collection Name> --file $filename; done
    
    0 讨论(0)
  • 2020-11-30 00:29

    Another one line solution (assuming you are in the folder where the json files are):

    ls | sed 's/.json$//' | xargs -I{} mongoimport -d DATABASE_NAME -c {} {}.json
    
    0 讨论(0)
  • 2020-11-30 00:30

    Linux:

    > cat one.json two.json > three.json
    
    > mongoimport --db foo --collection baz --file three.json"
    

    Or, all files in the folder :

    > cat *.json > big.json
    
    > mongoimport --db foo --collection baz --file "big.json"
    
    0 讨论(0)
  • 2020-11-30 00:32

    I came up with a more elegant way to automatically import ALL collections:

    ls -1 *.json | sed 's/.json$//' | while read col; do 
        mongoimport -d db_name -c $col < $col.json; 
    done
    

    I hope this is helpful.

    0 讨论(0)
  • 2020-11-30 00:36

    This worked for me in MAC OS X

    find . -regex '.*/[^/]*.json' | xargs -L 1 mongoimport --db DB_NAME -u USER_NAME -p PASSWORD --collection COLLECTION_NAME  --file
    
    0 讨论(0)
  • 2020-11-30 00:36

    I'm going to show how to import many collections efficiently using only the Linux's terminal (it also works in Mac).

    You must have all json files at the same folder and the file's name should be the collection that will be imported to your database.

    So, let's begin, open the folder that contains your json files. Replace the <DATABASE> to your database name, then execute the line below:

    for collection in $(ls | cut -d'.' -f1); do mongoimport --db <DATABASE> --collection ${collection} --file ${collection}.json; done

    But what is going on there?

    First of all, you have to keep in mind that the parentheses will be executed first. In this case, it creates a list of all files getting just the name of each file (removing it's extension).

    Secondly, all list will be added to a loop "for" in a local variable called collection (this variable's name could be anything you want)

    Thirdly, the "do" execute the import line(*)

    Finally the "done", finish the loop.

    (*) The import line is composed by "mongoimport" that requires the database name "--db", the collection name "--collection", and the file name "--file". These requirements has been filled by the variable "$collection" created on the "for" stuff

    I hope helped someone! Good luck guys :)

    0 讨论(0)
提交回复
热议问题