官术网_书友最值得收藏!

Importing a CSV file into MongoDB

Importing data from a CSV file into MongoDB is one of the fastest methods of import available. It is also one of the easiest. With almost every database system exporting to CSV, the following recipe is sure to come in handy.

Getting ready

The UK Road Safety Data comprises three CSV files: accidents7904.csv, casualty7904.csv, and vehicles7904.csv. Use this recipe to import the Accidents7904.csv file into MongoDB.

How to do it…

Run the following command at the command line:

./Applications/mongodb-3.0.4/bin/mongoimport --db pythonbicookbook --collection accidents --type csv --headerline --file '/Data/Stats19-Data1979-2004/Accidents7904.csv' --numInsertionWorkers 5

After running that command, you should see something similar to the following screenshot:

The following command is what you would use for Windows:

C:\Program Files\MongoDB\Server\3.0\bin\mongoimport --db pythonbicookbook --collection accidents --type csv --headerline --file C:\Data\Stats19-Data1979-2004\Accidents7904.csv --numInsertionWorkers 5

How it works…

Each part of the command has a specific function:

  • ./Application/mongodb-3.0.4/mongoimport: The MongoDB utility that we will use to import the data.
  • -- db pythonbicookbook: Specifies the name of the database to use.
  • -- collection accidents: Tells the tool the name of the collection to use; if the collection doesn't exist, it will be created automatically.
  • --type csv: Specifies that we're importing a CSV file.
  • --headerline: Tells the import tool that our CSV file has a headerline containing the column headers.
  • --file '/Data/Stats19-Data1979-2004/Accidents7904.csv': The full path to the file which contains the data that we're importing.
  • --numInsertionWorkers 5: By default, MongoDB uses a single worker to import the data. To speed this up, we specify the use of 5 workers.

There's more…

You can import data from another computer in MongoDB:

Tip

Importing into a MongoDB instance running on another computer

If you need to import data into a non-local instance of MongoDB, use the --host <hostname><:port> options. Otherwise, mongoimport assumes that you are importing into a local MongoDB instance.

主站蜘蛛池模板: 灵石县| 临泽县| 呼图壁县| 友谊县| 龙川县| 门源| 磐石市| 城固县| 青浦区| 沂水县| 乐都县| 长白| 昌平区| 乌拉特中旗| 潼关县| 牙克石市| 西丰县| 黄梅县| 永寿县| 白银市| 永年县| 承德市| 民和| 邛崃市| 武宣县| 商河县| 永寿县| 临桂县| 诸城市| 北京市| 新龙县| 马山县| 孙吴县| 西贡区| 清新县| 珲春市| 郁南县| 望都县| 木兰县| 桐城市| 石屏县|