MongoDB整理筆記の匯入匯出

來源:互聯網
上載者:User

標籤:

  一、匯入

    1、匯入json資料

    我們先將表user刪除掉,以便示範效果:

> db.user.drop(); true > show collections; system.indexes

    然後匯入資料

[[email protected] bin]#./mongoimport -d my_mongodb -c user user.dat connected to: 127.0.0.1 imported 2 objects [[email protected] bin]#

    可以看到匯入資料的時候會隱式建立表結構
    2、匯入csv資料

    我們先講標user刪除掉,以便示範效果

> db.user.drop(); true  > show collections; system.indexes > 

    然後匯入資料 

[[email protected] bin]# ./mongoimport -d my_mongodb -c user --type csv --headerline --file user_csv.datconnected to: 127.0.0.1 imported 3 objects [[email protected] bin]#

    參數說明

    type  指明要匯入的檔案格式

    headerline 指明不匯入第一行

    file 指明要匯入的檔案路徑
   !!!注意:CSV格式更好,主流資料庫都支援匯出為CSV格式,所以這種格式非常利於異構資料移轉。

    二、匯出

    假設庫裡有一張user表,裡面有2條記錄,我們要將它匯出

> use my_mongodb  switched to db my_mongodb > db.user.find();  { "_id" : ObjectId("4f81a4a1779282ca68fd8a5a"), "uid" : 2, "username" : "Jerry", "age" : 100 } { "_id" : ObjectId("4f844d1847d25a9ce5f120c4"), "uid" : 1, "username" : "Tom", "age" : 25 } > 

    同樣,匯出也有兩種方式:json格式以及CSV格式。

    先來json格式

[[email protected] bin]# ./mongoexport -d my_mongodb -c user -o user.datconnected to: 127.0.0.1 exported 2 records  [[email protected] bin]# cat user.dat  { "_id" : { "$oid" : "4f81a4a1779282ca68fd8a5a" }, "uid" : 2, "username" : "Jerry", "age" : 100 } { "_id" : { "$oid" : "4f844d1847d25a9ce5f120c4" }, "uid" : 1, "username" : "Tom", "age" : 25 } [[email protected] bin]# 

    參數說明

    d 指明使用的庫

    c 指明要匯出的表

    o 指明要匯出的檔案名稱

    再來CSV格式

[[email protected] bin]# ./mongoexport -d my_mongodb -c user --csv -f uid,username,age-o user_csv.datconnected to: 127.0.0.1 exported 2 records  [[email protected] bin]# cat user_csv.dat uid,username,age 2,"Jerry",100 1,"Tom",25  [[email protected] bin]#

    參數說明:

    csv 指明要匯出為CSV格式

    f 指明要匯出哪些列

    更詳細用法可以輸入命令mongoexport -help來查看 

    需要注意的:其實mongodb匯出是可以按條件的,比如如下匯出的是5月12號整天的資料。

/usr/local/mongodb/bin/mongoexport -h 192.168.100.109 --port 27017 -d test -c testdb -q "{\"initTime\":{$gte:\"2014-05-12 00:00:00\",$lte:\"2014-05-12 23:59:59\"}}" -o test.txt  

    說明

    1、集合結構中必須要有時間的域,我的是initTime

    2、-q參數裡面放入的是你需要指定的條件

    3、注意-q 最外層的是雙引號,而裡面的雙引號都加上轉義符“\”

    4、以此類推,如果集合結構中有性別,則可指定性別匯出;有年齡,則可指定年齡匯出...

    5、用戶端同樣可以匯出伺服器資料,格式:--host 192.168.100.109 --port 27017

 

MongoDB整理筆記の匯入匯出

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.