2020-04-26

使用 mongo shell 建立資料庫

使用 mongo shell 建立資料庫

在 Mac 安裝好 MongoDB 後,在 terminal 輸入 mongo 即可進入 mongo shell,以下是建立資料庫和 collections 的方式:

> show databases # 顯示所有資料庫列表 admin 0.000GB config 0.000GB local 0.000GB

Mongo shell 沒有 create database 之類的指令,而是直接使用 use,不論該資料庫是否存在。使用新的 collection 也是同樣的情況。

> use test #切換到現有的資料庫或新資料庫 switched to db test > db #查看目前操作的資料庫 test > db.testCol.insertOne({a:1}) #直接在新的 collection 新增資料 { "acknowledged" : true, "insertedId" : ObjectId("5ea46d5864bc492ceab2d55e") } > show collections #顯示資料庫內的 collections testCol > db.dropDatabase() #刪除資料庫,沒事別亂用 { "dropped" : "test", "ok" : 1 } >

MongoDB 的核心是 JavaScript 引擎,mongo shell 在很多地方用起來也像是在寫 JS 一樣。

另外,官方有使用 mongoimport 滙入資料的說明在 https://docs.mongodb.com/guides/server/import/。 以下是沒使用帳密的滙入方式:

$ mongoimport --db test --collection inventory --file ~/downloads/inventory.crud.json 2020-04-26T01:20:28.490+0800 connected to: mongodb://localhost/ 2020-04-26T01:20:28.981+0800 5 document(s) imported successfully. 0 document(s) failed to import. $

滙出資料的說明在 https://docs.mongodb.com/manual/reference/program/mongoexport/

$ mongoexport --collection=inventory --db=test --out=/Users/shinder/downloads/inventory.json 2020-04-26T01:30:09.932+0800 connected to: mongodb://localhost/ 2020-04-26T01:30:10.641+0800 exported 5 records $

沒有留言:

FB 留言