下載:https://www.mongodb.com
文檔:https://docs.mongodb.com/manual/
下載好之后雙擊進行安裝蜘澜,win7系統(tǒng)需要安裝補丁,KB2731284荸实。
直接下一步下一步安裝完成届垫。
安裝完之后配置環(huán)境變量:
把MongoDB安裝目錄加在Path后面,用分號隔開泊藕。
那么我們就能在系統(tǒng)的任何盤符载佳,使用mongo命令了:
mongo 使用數(shù)據(jù)庫
mongod 啟動服務
mongoimport 導入數(shù)據(jù)
啟動數(shù)據(jù)庫:
--dbpath
就是選擇數(shù)據(jù)庫文檔所在的文件夾炒事。
show dbs:列出所有數(shù)據(jù)庫
use 數(shù)據(jù)庫名字:使用某個數(shù)據(jù)庫
db:查看當前所在數(shù)據(jù)庫
如果想新建數(shù)據(jù)庫,也是use
刚盈,use
一個不存在的羡洛,就是新建。
student就是所謂的集合藕漱。集合中存儲著很多json欲侮。
student是第一次使用,集合將自動創(chuàng)建肋联。
使用數(shù)據(jù)庫
- 要使用數(shù)據(jù)庫威蕉,干的第一件事情就是啟動服務:
mongod --dbpath '數(shù)據(jù)庫的位置'
例如:mongod --dbpath c:\mongo
- 查看所有數(shù)據(jù)列表:
show dbs
- 查看所有集合:
show collections
- 可以查看集合中的語句:
db.student.find()
- 使用數(shù)據(jù)庫,創(chuàng)建數(shù)據(jù)庫:
use student
注意:如果真的想把這個數(shù)據(jù)庫創(chuàng)建成功橄仍,那么必須插入一個數(shù)據(jù)韧涨。
數(shù)據(jù)庫中不能直接插入數(shù)據(jù),只能往集合(collections)中插入數(shù)據(jù),不需要創(chuàng)建集合侮繁,只需要寫點語法
比如往user這個集合中插入一條數(shù)據(jù):
db.user.insert({"name":"xiaoming","age":"20"})
這時就創(chuàng)建 了一個user這個集合
- 刪除數(shù)據(jù)庫虑粥,刪除當前所在的數(shù)據(jù)庫:
db.dropDatabase();
使用db
命令可以查看當前使用的是那個數(shù)據(jù)庫 - 插入數(shù)據(jù):
db.user.insert({"name":"xiaoming","age":"20"})
- 我們不可能一條一條的
insert
,所以宪哩,我們希望用記事本在外部寫好數(shù)據(jù)庫的形式娩贷,然后使用mongoimport導入數(shù)據(jù)庫:
mongoimport --db test --collection restaurants --drop --file primer-dataset.json
-db test
:想往哪個數(shù)據(jù)庫里面導入
--collection restaurants
: 想往哪個集合中導入
--drop
:把集合清空
--file primer-dataset.json
: 哪個文件
查找數(shù)據(jù)用find;
db.restaurants.find()
如果find中沒有數(shù)據(jù),將查出集合中所有文檔锁孟。
精確匹配:在student集合中查找數(shù)學成績?yōu)?0分的學生
db.student.find({"score.shuxue":70});
- 多個條件:查找數(shù)學成績?yōu)?0彬祖,且年齡為12 的學生
db.student.find({"score.shuxue":70 , "age":12})
- 大于條件:查找語文成績大于50的
db.student.find({"score.yuwen":{$gt:50}});
- 尋找所有年齡是9歲,或者11歲的學生
db.student.find( { $or:[{"age":9},{"age":11}] } );
- 查找完畢之后品抽,打點調(diào)用sort储笑,表示升降排序。
查找所有同學圆恤,按照語文成績從高到低排突倍,如果相同,按年齡從小到大排:
db.student.find().sort( { "score.yuwen": -1, "age": 1 } )
修改數(shù)據(jù)
- 查找名字叫做小明的,把年齡更改為16歲:
db.student.update({"name":"小明"},{$set:{"age":16}});
- 查找數(shù)學成績是70赘方,把年齡更改為33歲:
db.student.update({"score.shuxue":70},{$set:{"age":33}});
- 更改所有匹配項目:
db.student.update({"sex":"男"},{$set:{"age":33}},{multi: true});
加上
{multi: true}
這個條件可已更改所有匹配項
- 完整替換烧颖,不出現(xiàn)
$set
關鍵字了:
db.student.update({"name":"小明"},{"name":"大明","age":16});
刪除數(shù)據(jù)
刪除數(shù)學成績?yōu)?0分的
db.student.remove({"score.shuxue":"80"})
這樣的話是刪除所所有滿足條件的弱左,如果只想刪除一個窄陡,加{ justOne: true }
屬性。
db.student.remove({"score.shuxue":"80"},{ justOne: true })