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