前一篇博文說明了如何在win7下安裝mongodb,下面簡要測試一下nodejs操作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); } });
更多資料請參見nodejs mongodb官網? http://mongodb.github.io/node-mongodb-native/ ?和mongodb官網 http://www.mongodb.org/
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
