資料庫mongodb 的增刪改查
資料庫mongodb
MongoDB是基於分散式檔案儲存的資料庫。
資料庫命名:
通過識別符號,一般是utf-8字串,不能為空,不能用local/admin/config這三個。
文件
文件是一個鍵值(key-value)對MongoDB 的文件不需要設定相同的欄位,並且相同的欄位不需要相同的資料型別,這與關係型資料庫有很大的區別,也是 MongoDB 非常突出的特點。
集合
集合就是 MongoDB 文件組,類似於 RDBMS (關係資料庫管理系統:Relational Database Management System)中的表格。
集合存在於資料庫中,集合沒有固定的結構,這意味著你在對集合可以插入不同格式和型別的資料,但通常情況下我們插入集合的資料都會有一定的關聯性。集合的命名不能是空字串,也不能出現-,
ObjectId
ObjectId 類似唯一主鍵,可以很快的去生成和排序.
MongoDB 中儲存的文件必須有一個 _id 鍵。這個鍵的值可以是任何型別的,預設是個 ObjectId 物件。
MongoDB安裝
一、下載地址https://www.mongodb.com/download-center/community
二、命令列下執行 MongoDB 伺服器為了從命令提示符下執行MongoDB伺服器,你必須從MongoDB目錄的bin目錄中執行mongod.exe檔案。
終端中進入 C:\Program Files\MongoDB\Server\4.0\bin 目錄。
然後終端中輸入mongod就可以啟動MongoDB伺服器。
如果啟動不成功,可能是沒有db的路徑,所以指令輸入
mongod --dbkpath 建立db檔案的路徑E:/db
當你看到 waiting for connections on port 27017 的時候就是資料庫啟動成功了。
三、控制檯中使用mongo(終端中進入mongo的安裝目錄的bin下)
命令列操作 Mongodb
MongoDB的視覺化工具:Robo3T 或者noSql booster
MongoDB 命令
db.集合名(檔名).方法名
插入文件 insert()
db.post.insert()//在post中插入文件
db.psot.insertOne({})//在post中插入一個文件
db.post.insertMany({},{})//在post中插入多個
查詢文件 find()
db.post.find({})//不傳引數是查詢全部,傳入鍵值是查詢包含該鍵值的文件
db.post.findOne({})//只查詢一條
更新文件 update()
db.posts.update({title: "aaa"}, {$set: {age: 'changeName'}});
第一條是查詢到符合條件的文件,第二條是更新的內容 $set後面是修改的內容
db.post.updata({name: 'Lisi'}, {$inc: {age: 50}});
$inc 是讓其自己正加上響應的數字
刪除文件delete()
db.post.delete({})//不傳引數是刪除全部,傳入鍵值是刪除包含該鍵值的文件
db.post.deleteOne({})//傳入鍵值,只刪除一個
條件查詢
範圍查詢
關鍵字 |
含義 |
= |
相等 |
$gt |
>大於號 |
$lt |
< 小於號 |
$lte |
=< 小於等於號 |
$gte |
>= 大於等於號 |
例:
查詢age = 22的記錄
db.userInfo.find({"age": 22}); 相當於: select * from userInfo where age = 22;
查詢age > 22的記錄
db.userInfo.find({age: {$gt: 22}}); 相當於:select * from userInfo where age >22;
查詢age < 22的記錄
db.userInfo.find({age: {$lt: 22}}); 相當於:select * from userInfo where age <22;
查詢age >= 25的記錄
db.userInfo.find({age: {$gte: 25}}); 相當於:select * from userInfo where age >= 25;
查詢age <= 25的記錄
db.userInfo.find({age: {$lte: 25}});
查詢age >= 23 並且 age <= 26
db.userInfo.find({age: {$gte: 23, $lte: 26}});
模糊查詢
查詢name中包含mongo的資料
db.userInfo.find({name: /mongo/}); //相當於%% select * from userInfo where name like ‘%mongo%’;
並且條件: 查詢時一個物件中傳入兩個鍵值,中間用逗號隔開,
db.userInfo.find({name: 'zhangsan', age: 22【】});相當於:select * from userInfo where name = ‘zhangsan' and age = ’22';
或者條件 {$or :[{},{}]}滿足一個條件就能查出來
db.userInfo.find({$or: [{age: 22}, {age: 25}]});相當於:select * from userInfo where age = 22 or age = 25;
篩選資料
查詢指定列name、age資料,在需要查詢的物件之後再加入一個物件
{ name:1} 表示顯示name這一項。
db.user.find({}, {name: 1, age: 1});
//相當於:select name, age from userInfo;
查詢指定列name、age資料, age > 25
db.userInfo.find({age: {$gt: 25}}, {name: 1, age: 1});
相當於:select name, age from userInfo where age >25;
limit與skip方法
查詢前幾條資料 limit()
例:查詢前5條資料
db.userInfo.find().limit(5); 相當於:select top 5 * from userInfo;
查詢幾條之後的資料 skip()
例: 查詢10條之後的資料
db.userInfo.find().skip(10); 相當於:select * from userInfo where id not in ( select top 10 * from userInfo );
限制資料量/幾條資料
例:db.userInfo.find().limit(10).skip(5);
排序sort()
1代表升序,-1代表降序
例: 升序:db.userInfo.find().sort({age: 1});
降序:db.userInfo.find().sort({age: -1});
Mongoose的使用
安裝mongoose npm i mongoose
引入模組,連線資料庫
建立models資料夾,新建index.js
let mongoose = require('mongoose'); // 連結資料庫 mongoose.connect('mongodb://localhost:27017/zhili').then(data=>{ console.log("連結成功") }).catch(err=>{ console.log(err) });
地址的冒號後面是啟動資料庫之後的那個返回的資料27017。在後面的/zhili是選擇想要連結的資料庫
schema(提要,剛要,表)
// 新建表(集合) let Schema = mongoose.Schema // 新建文章表,命名規則是 let ArticleSchema = new Schema({ title:String,//文章標題 title 是字串型別 body:String,//文章內容 author:String, comments:[{body:String,date:Date}],//評論 hidden:{ type:Boolean,// 文章是否能被普通使用者看見 default:false }, favs:{ type:Number,//預設 點贊次數0 default:0 } } ,{ timestamps:true//增加兩個欄位 記錄 建立時間 修改時間 })
根據表明和結構得到資料庫模型
// 根據表名 和 表結構 得到資料庫模型 let Article = mongoose.model('Article',ArticleSchema) // 根據資料庫模型 操作 資料 增刪改查
插入資料
// 插入資料 let a1 = new Article({ title:"aaa", body:"HDSDFJKDF", author:"DNASJFN", comments:[{body:"FSLKDJF",date:new Date()}], favs:888 }) a1.save().then(res=>{ console.log("插入成功"+res) }).catch(err=>{ console.log(err) })
刪除資料
//刪除 //根據id刪除 Article.deleteOne({_id:"5f0eaf26dea3bc22d8e77843"}).then(res=>{ console.log(res) }) //根據id查詢 並且刪除 Article.findByIdAndDelete('5f0eaf890248d70ac001ccb8').then(res=>{ console.log(res) })
修改資料
// 修改 Article.updateOne({_id:"5f0eaf8c2367ce1a206332e3"},{body:"今天週三"}).then(res=>{ console.log(res) }) Article.updateOne({_id:"5f0eaf8c2367ce1a206332e3"},{$inc:{favs:1}}).then(res=>{ console.log(res) })
查詢資料。findById()
// 查 Article.findById('5f0eaf8c2367ce1a206332e3').then(res=>{ console.log(res) }) Article.findOne({title:"11",body:"22"}).then(res=>{ console.log(res) })
在終端中返回值
Article.find().then(res=>{
console.log(res)
})