2014-10-10 00:00

[API-d11] - MongoDB - Hello World!

今天先講在 Server 中如何操作 MongoDB

一樣開啟虛擬機,

我們在先前已經有先安裝過 MongoDB 了,因此,在 Ubuntu Server 中預設是開機啟動的

登入虛擬機吧~

登入虛擬機後,我們要進入 MongoDB,必須使用 mongo 這個 MongoDB Shell

$ mongo
MongoDB shell version: 2.6.4
connecting to: test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
	http://docs.mongodb.org/
Questions? Try the support group
	http://groups.google.com/group/mongodb-user
>  

此時會發現輸入指令的地方變成了 > 表示我們已經在 mongodb 裡面了

為什麼不需要帳號密碼即可進入 MongoDB 呢,因為 MongoDB 預設是不需要做登入的

並且加上預設只能由本機存取,也就是說,外部連入的 IP 是進不了 MongoDB 的

這部分後面會再作說明。

傳統的 Table 在 MongoDB 中,稱之為 Collection

一筆 record 在 MongoDB 中,稱之為 document

進入 MongoDB 後,

就可以簡單操作一些指令:

查詢所有的 DB:

> show databases;
admin  (empty)
local  0.078GB

切換 DB

> use test;

use DBNAME 若 DBNAME 不存在於 MongoDB 中的話,

等同於建立一個新的 DB,意思就是我們不需要下 ‘建立 DB’ 這個指令,

直接 use 就是一個新的 DB 了,不過這個 DB 會直到有 Collection 被新增才算真正的被建立

意即如果我們 use 了一個新的 DB,但是並沒有做任何新增 Collection 的動作就離開,

這個 DB 也不會被建立起來

當我們使用 use DBNAME 進入 DB 後:

###新增 Collection

> db.createCollection("TestCollection")
{ "ok" : 1 }

###CRUD 操作

此時 Collection “TestCollection” 就被建立了, 可以使用:

####新增資料:

example: db.TestCollection.insert(DATA);

DATA 就是 javascript 的 array map

> db.TestCollection.insert({data: "test_data", num: 2, arr: ["arr1", "arr2", "arr3"]});

####查詢資料

example: db.TestCollection.find(WHERE_CONDITION);

> db.TestCollection.find({data: "test_data"});
{ "_id" : ObjectId("5430497db94bb4afe2f8b387"), "data" : "test_data", "num" : 2, "arr" : [ "arr1", "arr2", "arr3" ] }

p.s. 每插入一筆資料,MongoDB 預設都會給訂一組 ObjectId

####查詢所有資料

> db.TestCollection.find();
{ "_id" : ObjectId("5430497db94bb4afe2f8b387"), "data" : "test_data", "num" : 2, "arr" : [ "arr1", "arr2", "arr3" ] }

####修改資料

example: db.TestCollection.update(WHERE_CONDITION, SET);

> db.TestCollection.update({data: "test_data"}, { $set: {num: 3} });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

// 查看 num 是否從 2 變 3 了
> db.TestCollection.find({data: "test_data"});
{ "_id" : ObjectId("5430497db94bb4afe2f8b387"), "data" : "test_data", "num" : 3, "arr" : [ "arr1", "arr2", "arr3" ] }

####刪除資料

exmaple: db.TestCollection.remove(WHERE_CONDITION);

> db.TestCollection.remove({data: "test_data"});

###刪除 Collection

> db.TestCollection.drop();

###查詢有哪些 Collection

> show collections;

###砍掉目前所在的整個 DB:

> use test;
> db.dropDatabase();
{ "dropped" : "test", "ok" : 1 }

tips: 在 mongo shell 裡有自動補完的功能,可以按下 tab 來查看有什麼方法可以用

ctrl-D 離開 Mongo Shell

MongoDB 官網文件非常詳細,可以多看看

明天會用 Node.js 的 MongoDB driver 來操作 MongoDB!

Share

comments powered by Disqus