How to import and export data on MongoDB

little bottle
Release: 2023-04-06 07:34:02
forward
3855 people have browsed it

MongoDB is a database based on distributed file storage. Below I will give you a brief description of the import and export of MongoDB. Interested friends can learn more.

1. Import and export can operate local mongodb or remote mongodb,Common options:

-h host   主机
--port port    端口
-u username 用户名
-p password   密码
Copy after login

If mongodb does not have an account password and is imported from local, you can ignore the above four parameters

2. Export:

Use mongodb/bin/mongoexport file:

cd /usr/local/mongodb
./bin/mongoexport -d shop -c order -f name,content -q '{_id:{$lte:100}}' -o order.json
-d  库名
-c  表名
-f  field1,field2...要导出的字段
-q  查询条件
-o  导出的文件名  
Copy after login

The default exported data format is json format. If you want to export csv format to facilitate data exchange with traditional databases, you need to specify the file type--csv. The above export command can Modify to:

./bin/mongoexport -d shop -c order -f name,content -q '{_id:{$lte:100}}' --csv -o order.csv
Copy after login

3. Import:

./bin/mongoimport -d shop -c good --type json --file ./order.json
-d 导入的数据库
-c 导入的表(不存在自动创建)
--type  csv | json(默认json)
--file 文件路径
Copy after login

Note: When the imported file format is csv, you need to add a --headerline, use the first line as Field name:

./bin/mongoimport -d shop -c good --type csv --headerline --file ./order.csv
Copy after login

4. Binary export

mongodump Export binarybson structure data and json structure index information

./bin/mongodump -d shop  -c order 
-d  库名
-c  表名(不指定表默认导出全部表)
-q  查询表达式
-o  文件路径名(默认导出到mongodb/dump目录下)
Copy after login

After exporting, there will be a .bson file and a .json file in the mongodb/dump/databaseName/ directory

[root@sx45a8 mongodb]# cd dump
[root@sx45a8 dump]# ls
shop
[root@sx45a8 dump]# cd shop
[root@sx45a8 shop]# ls
order.bson  order.metadata.json
Copy after login

5. Binary import

./bin/mongorestore -d test --dir dump/shop/
-d 导入的库名
--dir 文件目录
Copy after login

Binary backup can not only back up data but also back up indexes, and the backup is relatively small

Related tutorials: MongoDB video tutorial

The above is the detailed content of How to import and export data on MongoDB. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template