使用nodejs連接mongodb數(shù)據(jù)庫

一個(gè)簡單的nodejs連接mongodb示例钓辆,來自 mongodb官方示例

1. 創(chuàng)建package.json

首先肴焊,創(chuàng)建我們的工程目錄connect-mongodb,并作為我們的當(dāng)前目錄

mkdir connect-mongodb
cd connect-mongodb

輸入npm init命令創(chuàng)建package.json

npm init

然后蛀恩,安裝mongodb的nodejs版本driver
npm install mongodb --save
mongodb驅(qū)動(dòng)包將會(huì)安裝到當(dāng)前目錄下的node_modules中

2. 啟動(dòng)MongoDB服務(wù)器

安裝MongoDB并啟動(dòng)MongoDB數(shù)據(jù)庫服務(wù)茂浮,可參考我之前的文章壳咕,或者M(jìn)ongoDB官方文檔

3. 連接MongoDB

創(chuàng)建一個(gè)app.js文件顽馋,并添加以下代碼來連接服務(wù)器地址為192.168.0.243,mongodb端口為27017上名稱為myNewDatabase的數(shù)據(jù)庫

var MongoClient = require('mongodb').MongoClient,
    assert = require('assert');

// Connection URL
var url = 'mongodb://192.168.0.243:27017/myNewDatabase';

MongoClient.connect(url,function(err,db){
    assert.equal(null,err);
    console.log("Connection successfully to server");
    db.close();
});

在命令行輸入以下命令運(yùn)行app.js
node app.js

4. 插入文檔

app.js中添加以下代碼竟稳,使用insertMany方法添加3個(gè)文檔到documents集合中

var insertDocuments = function(db, callback){
    // get ths documents collection
    var collection = db.collection('documents');

    // insert some documents
    collection.insertMany([
        {a:1},{a:2},{a:3}
    ],function(err,result){
        assert.equal(err,null);
        assert.equal(3,result.result.n);
        assert.equal(3,result.ops.length);
        console.log("Inserted 3 documents into the collection");
        callback(result);
    });
};

insert命令返回一個(gè)包含以下屬性的對(duì)象:

  • result MongoDB返回的文檔結(jié)果
  • ops 添加了_id字段的文檔
  • connection 執(zhí)行插入操作所使用的connection

app.js更新以下代碼調(diào)用insertDocuments方法

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  insertDocuments(db, function() {
    db.close();
  });
});

在命令行中使用node app.js運(yùn)行

5. 查詢所有文檔

添加findDocuments函數(shù)

var findDocuments = function(db,callback){
    // get the documents collection
    var collection = db.collection('documents');
    // find some documents
    collection.find({}).toArray(function(err,docs){
        assert.equal(err,null);
        console.log("Found the following records");
        console.log(docs);
        callback(docs);
    });
};

findDocuments函數(shù)查詢了所有'documents'集合中所有的文檔他爸,將此函數(shù)添加到MongoClient.connect的回調(diào)函數(shù)中

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected correctly to server");

  insertDocuments(db, function() {
    findDocuments(db, function() {
      db.close();
    });
  });
});

6. 使用過濾條件(query filter)查詢文檔

查詢'a':3的文檔

var findDocuments = function(db, callback) {
  // Get the documents collection
  var collection = db.collection('documents');
  // Find some documents
  collection.find({'a': 3}).toArray(function(err, docs) {
    assert.equal(err, null);
    console.log("Found the following records");
    console.log(docs);
    callback(docs);
  });      
}

7. 更新文檔

var updateDocument = function(db,callback){
    // get the documents collection
    var collection = db.collection('documents');
    // update document where a is 2, set b equal to 1
    collection.updateOne({a:2},{
        $set:{b:1}
    },function(err,result){
        assert.equal(err,null);
        assert.equal(1,result.result.n);
        console.log("updated the document with the field a equal to 2");
        callback(result);
    });
};

updateDocument方法更新滿足條件a為2的第一個(gè)文檔诊笤,新增一個(gè)b屬性巾陕,并將其設(shè)置為1。
updateDocument方法添加到MongoClient.connect方法的回調(diào)中

MongoClient.connect(url,function(err,db){
    assert.equal(null,err);
    console.log("Connection successfully to server");
    insertDocuments(db,function(){
        updateDocument(db,function(){
            db.close();
        });
    });
});

8. 刪除文檔

var removeDocument = function(db,callback){
    // get the documents collection
    var collection = db.collection('documents');
    // remove some documents
    collection.deleteOne({a:3},function(err,result){
        assert.equal(err,null);
        assert.equal(1,result.result.n);
        console.log("removed the document with the field a equal to 3");
        callback(result);
    });
};

添加到app.js

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  insertDocuments(db, function() {
    updateDocument(db, function() {
      removeDocument(db, function() {
        db.close();
      });
    });
  });
});

9. 創(chuàng)建索引

索引能夠改善應(yīng)用的性能。下面你代碼在'a'屬性上添加索引

var indexCollection = function(db,callback){
    db.collection('documents').createIndex({
        a:1
    },null,function(err,results){
        console.log(results);
        callback();
    });
}; 

更新app.js

MongoClient.connect(url,function(err,db){
    assert.equal(null,err);
    console.log("Connection successfully to server");
    insertDocuments(db,function(){
        indexCollection(db,function(){
            db.close();
        });
    });
});

代碼已經(jīng)托管在碼云

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末凉馆,一起剝皮案震驚了整個(gè)濱河市乾巧,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌沟于,老刑警劉巖植康,帶你破解...
    沈念sama閱讀 216,372評(píng)論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件销睁,死亡現(xiàn)場離奇詭異,居然都是意外死亡冻记,警方通過查閱死者的電腦和手機(jī)冗栗,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門供搀,熙熙樓的掌柜王于貴愁眉苦臉地迎上來钠至,“玉大人,你說我怎么就攤上這事棉钧。” “怎么了的诵?”我有些...
    開封第一講書人閱讀 162,415評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵佑钾,是天一觀的道長。 經(jīng)常有香客問我瘪阁,道長邮偎,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,157評(píng)論 1 292
  • 正文 為了忘掉前任豁跑,我火速辦了婚禮泻云,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘宠纯。我一直安慰自己,他們只是感情好快集,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,171評(píng)論 6 388
  • 文/花漫 我一把揭開白布廉白。 她就那樣靜靜地躺著,像睡著了一般院溺。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上珍逸,一...
    開封第一講書人閱讀 51,125評(píng)論 1 297
  • 那天,我揣著相機(jī)與錄音痊班,去河邊找鬼摹量。 笑死,一個(gè)胖子當(dāng)著我的面吹牛缨称,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播器净,決...
    沈念sama閱讀 40,028評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼当凡,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼!你這毒婦竟也來了浪慌?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,887評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤权纤,失蹤者是張志新(化名)和其女友劉穎乌妒,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體古掏,經(jīng)...
    沈念sama閱讀 45,310評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡侦啸,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,533評(píng)論 2 332
  • 正文 我和宋清朗相戀三年匹中,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了豪诲。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片顶捷。...
    茶點(diǎn)故事閱讀 39,690評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡服赎,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出重虑,到底是詐尸還是另有隱情,我是刑警寧澤永高,帶...
    沈念sama閱讀 35,411評(píng)論 5 343
  • 正文 年R本政府宣布提针,位于F島的核電站,受9級(jí)特大地震影響辐脖,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜艇抠,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,004評(píng)論 3 325
  • 文/蒙蒙 一久锥、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧媒鼓,春花似錦、人聲如沸绿鸣。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽擎厢。三九已至,卻和暖如春动遭,著一層夾襖步出監(jiān)牢的瞬間神得,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評(píng)論 1 268
  • 我被黑心中介騙來泰國打工宵蕉, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人羡玛。 一個(gè)月前我還...
    沈念sama閱讀 47,693評(píng)論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像薄榛,于是被迫代替她去往敵國和親渺杉。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,577評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容