插入數(shù)據(jù)
- 插入多條數(shù)據(jù)
//要操作的數(shù)據(jù)庫的url,數(shù)據(jù)庫名為test
var url='mongodb://localhost:27017/test';
var insert_many = (db, callback)=> {
const collection=db.collection("users"); //連接到數(shù)據(jù)庫下的"users" collection
const data=[{name:"Look",age:"45"},
{name:"Rose",age:"27"}];
//insertMany()為操作數(shù)據(jù)庫的API
collection.insertMany(data,(err,result)=>{
if(err){
console.log("ERROR");
}else{
callback(result);
}
});
};
//連接數(shù)據(jù)庫
MongoClient.connect(url, (err,db)=> {
console.log("連接成功!");
insert_many(db,(result)=>{
console.log("成功插入多條數(shù)據(jù)");
});
});
- 刪除數(shù)據(jù)
var url='mongodb://localhost:27017/test';
var delete_one=(db,callback)=>{
const collection=db.collection("users");
collection.deleteOne({name:"Rose"},(err,result)=>{
if(err){
console.log("ERROR");
}else{
callback(result);
}
db.close();
})
};
MongoClient.connect(url, (err, db)=> {
console.log("連接成功喷户!");
delete_one(db,(result)=>{
console.log(result);
});
});
具有刪除功能的API還有deleteMany
,區(qū)別是:
deleteOne()
只會刪除查找到的第一條符合條件的數(shù)據(jù)
deleteMany()
會刪除所有查找到的符合條件的數(shù)據(jù)
- 修改數(shù)據(jù)
var url='mongodb://localhost:27017/test';
var update_one=(db,callback)=>{
const collection=db.collection("users");
collection.updateOne({name:"Rose"},{$set:{age:"30"}},(err,result)=>{
if(err){
console.log("ERROR");
}else{
callback(result);
}
db.close()
});
};
MongoClient.connect(url,(err,db)=>{
console.log("連接成功");
update_one(db,(result)=>{
console.log(result);
});
});
具有修改功能的API還有updateMany()
,區(qū)別和上邊類似,updateOne()
是修改一條數(shù)據(jù),而updateMany()
是修改所有數(shù)據(jù)
- 查找數(shù)據(jù)
//查找一條數(shù)據(jù)
var url='mongodb://localhost:27017/test';
var find_one = (db, callback)=> {
const collection=db.collection("users");
collection.findOne({name:"Bob"},(err,result)=>{
if(err){
console.log("ERROR");
}else{
console.log("查找成功");
callback(result);
}
db.close();
})
};
MongoClient.connect(url, (err, db)=> {
console.log("連接成功!");
find_one(db,(result)=>{
console.log(result);
});
});
//查找所有數(shù)據(jù)
const find_all=(db,callback)=>{
const collection=db.collection("users");
//查找 users 文檔中的所有數(shù)據(jù)
collection.find({}).toArray((err,result)=>{
if(err){
console.log("ERROR");
}else{
console.log(" callback before");
callback(result);
console.log("callback after");
}
});
};
MongoClient.connect(url,(err,db)=>{
//連接到表 users
console.log("連接成功蒂秘!");
find_all(db,(result)=>{
console.log(result.length);
for(var i=0;i<result.length;i++){
console.log(result[i]);
}
db.close();
});
});
本篇文章是Node.js操作數(shù)據(jù)庫的簡單用法矾麻,隨后還會有補(bǔ)充。
更多示例請點(diǎn)這里