本篇文章為大家展示了使用node.js怎么對mongodb進行操作,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
首先安裝nodejs mongodb
npm install mongodb
代碼
var mongodb = require('mongodb');
var server = new mongodb.Server('localhost', 27017, {auto_reconnect:true});
var db = new mongodb.Db('mydb', server, {safe:true});
//連接db
db.open(function(err, db){
if(!err){
console.log('connect db');
// 連接Collection(可以認為是mysql的table)
// 第1種連接方式
// db.collection('mycoll',{safe:true}, function(err, collection){
// if(err){
// console.log(err);
// }
// });
// 第2種連接方式
db.createCollection('mycoll', {safe:true}, function(err, collection){
if(err){
console.log(err);
}else{
//新增數據
// var tmp1 = {id:'1',title:'hello',number:1};
// collection.insert(tmp1,{safe:true},function(err, result){
// console.log(result);
// });
//更新數據
// collection.update({title:'hello'}, {$set:{number:3}}, {safe:true}, function(err, result){
// console.log(result);
// });
// 刪除數據
// collection.remove({title:'hello'},{safe:true},function(err,result){
// console.log(result);
// });
// console.log(collection);
// 查詢數據
var tmp1 = {title:'hello'};
var tmp2 = {title:'world'};
collection.insert([tmp1,tmp2],{safe:true},function(err,result){
console.log(result);
});
collection.find().toArray(function(err,docs){
console.log('find');
console.log(docs);
});
collection.findOne(function(err,doc){
console.log('findOne');
console.log(doc);
});
}
});
// console.log('delete ...');
// //刪除Collection
// db.dropCollection('mycoll',{safe:true},function(err,result){
// if(err){
// console.log('err:');
// console.log(err);
// }else{
// console.log('ok:');
// console.log(result);
// }
// });
}else{
console.log(err);
}
});上述內容就是使用node.js怎么對mongodb進行操作,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。