MongoDB數(shù)據(jù)庫常用的10條操作命令
1. 顯示全部可用數(shù)據(jù)庫
> show dbs;
該命令將展示 mongo 的全部數(shù)據(jù)庫名稱,并列出來。
2. 切換數(shù)據(jù)庫
> use mydb;
該命令會(huì)選擇一個(gè)指定的數(shù)據(jù)庫,如果數(shù)據(jù)庫不存在,則會(huì)自動(dòng)創(chuàng)建一個(gè)。但是需要注意,由于此時(shí)數(shù)據(jù)庫沒有數(shù)據(jù),因此當(dāng)使用 show dbs命令的時(shí)候,看不到該數(shù)據(jù)庫。只有插入了數(shù)據(jù)集后才可以看到。
3. 顯示數(shù)據(jù)集
> show collections;
4. 插入數(shù)據(jù)
插入數(shù)據(jù)的格式為 db.{數(shù)據(jù)集名}.insert({數(shù)據(jù)鍵值對(duì)}),成功后返回插入的條數(shù)。
> db.test.insert({"name": "島上碼農(nóng)"}); WriteResult({ "nInserted" : 1 })
插入多條數(shù)據(jù)使用中括號(hào)括起來即可,此時(shí)返回的是批量操作結(jié)果,其中 nInserted 返回的是成功插入的條數(shù)。。
> db.test.insert([{"name": "島上碼農(nóng)"},{"name": "掘金"}]); BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 2, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })
5. 更新數(shù)據(jù)
更新一條數(shù)據(jù)的命令如下,其中格式為 db.{數(shù)據(jù)集名}.update({查詢條件}, {$set: {更新后數(shù)據(jù)}})。
> db.test.update({"name": "島上碼農(nóng)"}, {$set: {"name": "碼農(nóng)"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
以上命令只會(huì)更新一條匹配的數(shù)據(jù),如果要更新多條,需要增加參數(shù):{multi: true}。
> db.test.update({"name": "島上碼農(nóng)"}, {$set: {"name": "碼農(nóng)"}}, {multi: true}); WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
也可以使用 updateMany 更新多條。
> db.test.updateMany({"name": "碼農(nóng)"}, {$set: {"name": "島上碼農(nóng)"}}); { "acknowledged" : true, "matchedCou
6. 替換文檔
替換文檔會(huì)使用新的文檔替換掉已有的文檔,其中格式為 db.{數(shù)據(jù)集名}.save({新文檔數(shù)據(jù)})。例如下面的例子替換了_id 為60c8a50adb9890bf41255fe4的文檔。
> db.test.save({"_id": "60c8a50adb9890bf41255fe4", "name": "島上碼農(nóng)-1"}); WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : "60c8a50adb9890bf41255fe4" })
7. 查詢數(shù)據(jù)
查詢數(shù)據(jù)命令為格式為 db.{數(shù)據(jù)集名}.find()。如果需要限制條數(shù)可以加limit(n)。
> db.test.find();
查詢出來的格式需要美化的話,加上 pretty()即可。
> db.test.find().pretty();
按條件查詢時(shí),在 find 中添加篩選參數(shù)即可。
> db.test.find({"name":"島上碼農(nóng)"}).pretty();
8. 統(tǒng)計(jì)條數(shù)
統(tǒng)計(jì)時(shí)使用 count()函數(shù)即可,如果需要篩選也是在 find 方法中傳篩選條件即可。
> db.test.find().count();
9. 刪除文檔
刪除文檔的格式為db.test.remove({篩選條件});
> db.test.remove({"name":"島上碼農(nóng)-1"}); WriteResult({ "nRemoved" : 1 })
刪除一條的使用 deleteOne 方法,刪除多條使用 deleteMany 方法。
> db.test.deleteOne({"name":"島上碼農(nóng)"}); { "acknowledged" : true, "deletedCou
10. 查看幫助文檔
對(duì)于有些命令不懂操作的,查看操作文檔即可,命令格式為 db.{數(shù)據(jù)集名}.help()。
以上就是MongoDB數(shù)據(jù)庫常用的10條操作命令的詳細(xì)內(nèi)容,更多關(guān)于MongoDB 操作命令的資料請(qǐng)關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。