MongoDB

Try MongoDB, http://try.mongodb.org/


Mongo Tutorial (by 勇達)

1. MongoDB 的用語(Terms):

[一般DB]   [MongoDB]
Database -> Database
Table -> Collection
Row -> Document

2. MongoDB 的基本操作 CRUD (Create, Read, Update and Delete)

(1) Create Database and a Collection 
> use <databaseName>
> db.createCollection (<name>)
E.g.: Create a Database named "myDatabase" and a Collection named "score"
> use myDatabase
> db.createCollection(score);

(2) Insert (Save) a record
> db.collectionName.save(<JSON document>);
E.g.: Save a document with name = Johnny, age=20, score=100
> db.score.save({"name":"Johnny","age":20,"score":100});
> db.score.save({"name":"William","age":25,"score":90,});
> db.score.save({"name":"Eric","age":30,"score":85,"language":["English","Chinese"]});

(3) Query record(s)
> db.score.find({key:value}>);
E.g.: Find documents that contain name == Johnny in "score" collection
> db.score.find({"name":"Johnny"});

(4) Update a record / row
> db.collectionName.update(<condition>,<the new fields({key:value,...})>);
E.g.: Update document with "name":"Johnny" to "name":"Ricky"
> db.score.update({"name":"Johnny"},{"name":"Ricky"});
Notes: This update will only replace the first document that matches to the <condition> and also all of the fields in the matching document will be replaced by <the new fields({key:value,...})>;
Modifier Operations: 
- $set 用來 update 某個 document 但是只針對某個 field 做 update. 
E.g.: 將 name == William 的document更新其 score 成 100 
> db.score.update({"name":"William"},{$set:{"score":100}});

- $push 用來增加一個元素(element)到 Document 的 某個欄位的 array 裡
E.g.: 將 Eric 的 language array 加一個 "Taiwanese"
> db.score.update({"name":"Eric"},{$push:{"language":"Taiwanese"}});

- $pop 用來移除(removes) document 中的array第一個元素或最後一個元素
E.g.: 將 Eric 的 language array 中的最後一個元素移除
> db.score.update({"name":"Eric"},{$pop:{"language":1}});
E.g.: 將 Eric 的 language array 中的第一個元素移除
> db.score.update({"name":"Eric"},{$pop:{"language":-1}});

- $pull 用來移除所有符合 key:value 的 array元素
E.g.: 將 Eric 的 language array 中符合 language == English 的移除
> db.score.update({"name":"Eric"},"{$pull:{"language":"English"}}");

3. Slides: see the attachment.

Ċ
William Artan,
Nov 20, 2011, 11:30 PM
Comments