MongoDB第一课,shell命令下的增删改查
查看所有數(shù)據(jù)庫列表
show dbs
?
使用數(shù)據(jù)庫、創(chuàng)建數(shù)據(jù)庫
use databasename
?
如果真的想把這個(gè)數(shù)據(jù)庫創(chuàng)建成功,那么必須插入一個(gè)數(shù)據(jù)。
數(shù)據(jù)庫中不能直接插入數(shù)據(jù),只能往集合(collections)中插入數(shù)據(jù)。不需要?jiǎng)?chuàng)建集合,只需要寫點(diǎn)語法:
db.student.insert({“name”:”xiaoming”});
db.student? 系統(tǒng)發(fā)現(xiàn)student是一個(gè)陌生的集合名字,所以就自動(dòng)創(chuàng)建了集合。
?
刪除數(shù)據(jù)庫,刪除當(dāng)前所在的數(shù)據(jù)庫
db.dropDatabase();
查看一個(gè)集合的信息:
?
1 插入數(shù)據(jù)
插入數(shù)據(jù),隨著數(shù)據(jù)的插入,數(shù)據(jù)庫創(chuàng)建成功了,集合也創(chuàng)建成功了。
| 1???????? db.student.insert({"name":"xiaoming"}); |
?
我們不可能一條一條的insert。所以,我們希望用sublime在外部寫好數(shù)據(jù)庫的形式,然后導(dǎo)入數(shù)據(jù)庫:
?
| 1???????? mongoimport --db test --collection restaurants --drop --file primer-dataset.json |
-db test? 想往哪個(gè)數(shù)據(jù)庫里面導(dǎo)入
--collection restaurants? 想往哪個(gè)集合中導(dǎo)入
--drop 把集合清空
--file primer-dataset.json? 哪個(gè)文件
?
這樣,我們就能用sublime創(chuàng)建一個(gè)json文件,然后用mongoimport命令導(dǎo)入,這樣學(xué)習(xí)數(shù)據(jù)庫非常方便。
?
2 查找數(shù)據(jù)
查找數(shù)據(jù),用find。find中沒有參數(shù),那么將列出這個(gè)集合的所有文檔:
| 1???????? db.restaurants.find() |
?
精確匹配:
| 1???????? db.student.find({"score.shuxue":70}); |
?
多個(gè)條件:
| 1???????? db.student.find({"score.shuxue":70 , "age":12}) |
?
大于條件:
| 1???????? db.student.find({"score.yuwen":{$gt:50}}); |
?
或者。尋找所有年齡是9歲,或者11歲的學(xué)生
| 1???????? db.student.find({$or:[{"age":9},{"age":11}]}); |
?
查找完畢之后,打點(diǎn)調(diào)用sort,表示升降排序。
| 1???????? db.restaurants.find().sort( { "borough": 1, "address.zipcode": 1 } ) |
?
3 修改數(shù)據(jù)
修改里面還有查詢條件。你要該誰,要告訴mongo。
查找名字叫做小明的,把年齡更改為16歲:
| 1???????? db.student.update({"name":"小明"},{$set:{"age":16}}); |
?
查找數(shù)學(xué)成績是70,把年齡更改為33歲:
| 1???????? db.student.update({"score.shuxue":70},{$set:{"age":33}}); |
?
更改所有匹配項(xiàng)目:"
By default, the update() method updates a single document. To update multiple documents, use the multi option in the update() method.
| 1???????? db.student.update({"sex":"男"},{$set:{"age":33}},{multi: true}); |
?
完整替換,不出現(xiàn)$set關(guān)鍵字了:
| 1???????? db.student.update({"name":"小明"},{"name":"大明","age":16}); |
?
4 刪除數(shù)據(jù)
?
| 1???????? db.restaurants.remove( { "borough": "Manhattan" } ) |
?
By default, the remove() method removes all documents that match the remove condition. Use the justOne option to limit the remove operation to only one of the matching documents.
?
| 1???????? db.restaurants.remove( { "borough": "Queens" }, { justOne: true } ) |
不過這些已經(jīng)比較老了,最新的寫法還是要看官方文檔,這部分寫的還是很清楚的,閱讀起來沒有問題?https://docs.mongodb.com/manual/tutorial/remove-documents/
?
轉(zhuǎn)載于:https://www.cnblogs.com/zhangmingzhao/p/7882686.html
總結(jié)
以上是生活随笔為你收集整理的MongoDB第一课,shell命令下的增删改查的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux目录管理类命令之ls
- 下一篇: 项目管理工具之maven