来源:http://francs3.blog.163.com/blog/static/405767272012101710594437
/
上篇BLOG 介绍了 MongoDB 集合的导出,今天接着学习集合导入,下面演示了
从一个库导出集合到另一个库的具体步骤,如下:
--基础信息
[mongo@redhatB ~]$ mongo
MongoDB shell version: 2.2.1
connecting to: test
> show dbs;
local (empty)
skytf 0.0625GB
test 0.0625GB
> show collections;
system.indexes
test_2
things
> use skytf;
switched to db skytf
> show collections;
system.indexes
test_1
|
备注:我们的目标是将 test 库的集合 things 导入到库 skytf
中。
一 以JSON
格式导入导出
--1.1 从源库导出集合
[mongo@redhatB tf]$ mongoexport -h 127.0.0.1
-d test -c things -v -o things.json
Sat Nov 17 10:21:27 creating new connection
to:127.0.0.1:27017
Sat Nov 17 10:21:27 BackgroundJob starting: ConnectBG
Sat Nov 17 10:21:27 connected connection!
connected to: 127.0.0.1
exported 30 records |
备注:导出库
test_2 的集合 things,从上面看出导出了 30 条记录。
--1.2 导入集合到目标库
[mongo@redhatB tf]$ mongoimport -h 127.0.0.1
-d skytf -c things --file things.json
connected to: 127.0.0.1
Sat Nov 17 10:28:30 imported 30 objects |
备注:从上看出导入了 30 个文档。
--1.3 查看目标库
> use skytf;
switched to db skytf
> show collections;
system.indexes
test_1
things
> db.things.count();
30
|
备注:集合 things 已经导入到数据库 skytf 中,并且导入了 30 个文档。
另外,导入集合时需要
指定 -c 参数,即目标的集合名,如果不指定会报以下 ERROR。
--1.4 导入集合时不指定集合 -c
参数
[mongo@redhatB tf]$ mongoimport -h 127.0.0.1
-d skytf --file things.json
connected to: 127.0.0.1
no collection specified! |
备注:当然也可以在目标库中指定与源库集合不同名的集合。 例如下例中,源库
skytf 库中的集合名为 things,可以指定目标库 skytf 的集合名为
things_1
--1.5
指定不同名的集合名
[mongo@redhatB tf]$ mongoimport -h 127.0.0.1
-d skytf -c things_1 --file things.json
connected to: 127.0.0.1
Sat Nov 17 10:30:11 imported 30 objects |
--1.6 再次查看目标库
> show collections;
system.indexes
test_1
things
things_1
> db.things_1.count();
30
|
二 以 CSV
格式导入导出
--2.1
从源库以CSV格式导出集合
[mongo@redhatB tf]$ mongoexport -h 127.0.0.1
-d test -c test_2 -f id,name,address --csv -o
test_2.csv
connected to: 127.0.0.1
exported 4 records |
--2.2 导入CSV数据到目标库
[mongo@redhatB tf]$ mongoimport -h 127.0.0.1
-d skytf -c test_2 --type csv
-f id,name,address
--headerline
--file test_2.csv
connected to: 127.0.0.1
Sat Nov 17 10:47:28 imported 4 objects |
备注:这里指定参数
--type csv 为导入 csv 格式数据; --headerline
表示CSV格式的第一行为字段,如果不指定
这个参数,则会将CSV格式第一行当数据导入到目标库。
--2.3 查看目标库
> use skytf;
switched to db skytf
> show collections;
system.indexes
test_1
test_2
things
things_1
> db.test_2.find();
{ "_id" : ObjectId("50a6fac0c32d362f080215fb"), "id" : 1, "name" :
"francs", "address" : "" }
{ "_id" : ObjectId("50a6fac0c32d362f080215fc"), "id" : 2, "name" :
"fpZhou", "address" : "" }
{ "_id" : ObjectId("50a6fac0c32d362f080215fd"), "id" : 3, "name" :
"tutu", "address" : "" }
{ "_id" : ObjectId("50a6fac0c32d362f080215fe"), "id" : 4, "name" :
"am", "address" : "zhoushan" }
|
三 参考
http://docs.mongodb.org/manual/reference/mongoimport/
http://blog.chinaunix.net/uid-26785103-id-3282144.html
加载中,请稍候......