MongoDB 常用的crud操作語句
對于后端大神(小白)來說,每天的工作就是 CRUD,再加上 Control + C 和 Control + V。作為大神(小白),怎么能不懂 CRUD 呢?MongoDB 的 CRUD 相比繁瑣的 SQL 語句而言十分簡便,顯得更為現(xiàn)代化。
創(chuàng)建數(shù)據(jù)(CREATE)
MongoDB 提供了兩種方式創(chuàng)建數(shù)據(jù):
db.crud.insert({name: '碼農', gender: '男'}); db.crud.save({name: ' 島上碼農', gender: '男'});
save 方法的不同之處在于如果攜帶有 _id屬性的話,就會更新對應數(shù)據(jù),否則就是插入新的數(shù)據(jù)。在 MongoDB 3.2以后新增了兩個插入方法:insertOne和insertMany,而 insert 方法已經(jīng)標記為廢棄。
db.crud.insertOne({name: '碼農', gender: '男'}); db.crud.insertMany([{name: '島上碼農', gender: '男'},{name: '程序媛', gender: '女'}]);
更新數(shù)據(jù)(Update)
更新時前面是查詢匹配條件,后面是需要更新的數(shù)據(jù)。
# 給一個碼農變性 db.crud.update({name: '碼農'}, {name: '碼農', gender: '女'});
update 方法默認是找到一條匹配的數(shù)據(jù)更新,而不是更新全部數(shù)據(jù),如果需要更新多條需要在后面增加屬性 multi: true。同時,需要注意文檔會被新的數(shù)據(jù)全部替換。
# 給全部碼農變性 db.crud.update({name: '碼農'}, {name: '碼農', gender: '女'}, {multi: true});
MongoDB 3.2版本后增加了 updateOne 和 updateMany 方法分別對應更新一條和多條數(shù)據(jù)。
# 恢復碼農的性別 db.crud.updateOne({name: '碼農'}, {$set: {name: '島上碼農', gender: '男'}}); db.crud.updateMany({name: '碼農'}, {$set: {name: '島上碼農', gender: '男'}});
在新版的 MongoDB 中,要求updateOne 和 updateMany 必須是原子操作,即必須指定使用 $set來指定更新的字段,以防止誤操作覆蓋掉整個文檔。如果不指定就會報錯:the update operation document must contain atomic operators。**推薦更新使用 ****updateOne**和 **updateMany**,更安全也更明確。 如果文檔需要被替換,可以使用 replaceOne:
db.crud.replaceOne({name: '島上碼農'}, {name: '程序媛', gender:'女'});
刪除(DELETE)
MongoDB 3.2版本后的刪除方法為 deleteOne 和 deleteMany,分布對應刪除一條和多條匹配的數(shù)據(jù)。
db.crud.deleteOne({name: '程序媛'}); db.crud.deleteMany({gender: '女'});
在早期的版本中,使用的是 remove 方法,remove如果第二個參數(shù)為 true 表示只刪除一條匹配的數(shù)據(jù)。。
db.crud.remove({name: '程序媛'}); db.crud.remove({gender: '女'}, true);
需要特別注意,如果使用的 remove 方法查詢參數(shù)對象為空,則會刪除全部數(shù)據(jù),這就要刪庫跑路的節(jié)奏了。
# 慎重操作,謹防刪庫跑路 db.crud.remove({});
讀取數(shù)據(jù)(READ)
讀取數(shù)據(jù)使用的是 find 或 findOne 方法,其中 find 會返回全部結果,當然也可以使用 limit 限制返回條數(shù)。
# 查詢全部數(shù)據(jù) db.crud.find(); # 只返回2條數(shù)據(jù) db.crud.find().limit(2); # 查詢名字為Tom 的數(shù)據(jù) db.crud.find({name: 'Tom'});
如果需要美化返回結果,則可以使用pretty()方法。
db.crud.find().limit(2).pretty();
如果要返回某些字段,則可以在后面指定返回的字段,如果要排除 _id 則需要顯示指定,其他字段不包含即可,否則會報錯:Cannot do exclusion on field gender in inclusion projection。
# 只返回_id和 name 字段 db.crud.find({name: 'Tom'}, {name: 1}); # 不返回_id db.crud.find({name: 'Tom'}, {_id: 0, name: 1});
以上就是MongoDB 常用的crud語句的詳細內容,更多關于MongoDB crud語句的資料請關注本站其它相關文章!
版權聲明:本站文章來源標注為YINGSOO的內容版權均為本站所有,歡迎引用、轉載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內容涉嫌侵權,請聯(lián)系alex-e#qq.com處理。