1、下載第三方模塊mongodb
cnpm install mongodb --save
2、檢測是否連接成功
1、引入第三方模塊mongodb並創建一個客戶端 const MongoClient = require("mongodb").MongoClient; 2、連接數據庫 //連接地址 const url = "mongodb://127.0.0.1:27017"; //連接數據庫的名稱 const db_name = "test"; //檢測是否連接成功 MongoClient.connect(url,(err,client)=>{ console.log(err,client); })
3、連接數據庫並選用數據庫中的哪張表
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://127.0.0.1:27017";
const db_name = "test";
MongoClient.connect(url,(err,client)=>{
//連接db_name這個數據庫並使用student這張表
const collection = client.db(db_name).collection('student');
})
4、增
//引入第三方模塊mongodb並創建一個客戶端 const MongoClient = require("mongodb").MongoClient; //定義連接的地址 const url = "mongodb://127.0.0.1"; //定義連接的數據庫 const db_name = "test"; //客戶端連接數據庫 MongoClient.connect(url,(err,client)=>{ //連接db_name這個數據庫並使用student這個表 const collection = client.db(db_name).collection("student"); //存入數據並退出連接 collection.save( { name:"德瑪西亞", age:25, sex:"男" }, (err,result)=>{ client.close(); } ) })
5、刪
//引入第三方模塊mongodb並創建一個客戶端 const MongoClient = require("mongodb").Mongoclient; //定義連接的地址 const url = "mongodb://127.0.0.1:27017"; //定義連接的數據庫 const db_name = "test"; //客戶端連接數據庫 MongoClient.connect(url,(err,client)=>{ //連接db_name這個數據庫並使用student這個表 const collection = client.db(db_name).collection("student"); //刪除指定數據並退出連接 collection.remove( { name:"德瑪西亞" }, (err,result)=>{ client.close(); } ) })
6、改
//引入第三方模塊mongodb並創建一個客戶端 const MongoClient = require("mongodb").MongoClient; //定義連接的地址 const url = "mongodb://127.0.0.1:27017"; //定義連接的數據庫 const db_name = "test"; //客戶端連接數據庫 MongoClient.connect(url,(err,client)=>{ //連接db_name這個數據庫並使用student這個表 const collection = client.db(db_name).collection("student"); //更新指定數據並退出連接 collection.update( { name:"德瑪西亞" }, { $set:{name:"提莫隊長"} } (err,result)=>{ client.close(); } ) })
7、查
//引入第三方模塊mongodb並創建一個客戶端 const MongoClient = require("mongodb").MongoClient; //定義連接的地址 const url = "mongodb://127.0.0.1:27017"; //定義連接的數據庫 const db_name = "test"; //客戶端連接數據庫 MongoClient.connect(url,(err,client)=>{ //連接db_name這個數據庫並使用student這個表 const collection = client.db(db_name).collection("student"); //查找到所有數據並轉化成一個數組 collection.find().toArray((err,result)=>{ console.log(result); client.close(); }) })