使用nodejs连接mongodb数据库

一个简单的nodejs连接mongodb示例,来自 mongodb官方示例

1. 创建package.json

首先,创建我们的工程目录connect-mongodb,并作为我们的当前目录

mkdir connect-mongodb
cd connect-mongodb

输入npm init命令创建package.json

npm init

然后,安装mongodb的nodejs版本driver
npm install mongodb --save
mongodb驱动包将会安装到当前目录下的node_modules中

2. 启动MongoDB服务器

安装MongoDB并启动MongoDB数据库服务,可参考我之前的文章,或者MongoDB官方文档

3. 连接MongoDB

创建一个app.js文件,并添加以下代码来连接服务器地址为192.168.0.243,mongodb端口为27017上名称为myNewDatabase的数据库

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();
});

在命令行输入以下命令运行app.js
node app.js

4. 插入文档

app.js中添加以下代码,使用insertMany方法添加3个文档到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命令返回一个包含以下属性的对象:

  • result MongoDB返回的文档结果
  • ops 添加了_id字段的文档
  • connection 执行插入操作所使用的connection

app.js更新以下代码调用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运行

5. 查询所有文档

添加findDocuments函数

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函数查询了所有'documents'集合中所有的文档,将此函数添加到MongoClient.connect的回调函数中

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的第一个文档,新增一个b属性,并将其设置为1。
updateDocument方法添加到MongoClient.connect方法的回调中

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. 创建索引

索引能够改善应用的性能。下面你代码在'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();
        });
    });
});

代码已经托管在码云

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,175评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,674评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,151评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,597评论 1 269
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,505评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,969评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,455评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,118评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,227评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,213评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,214评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,928评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,512评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,616评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,848评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,228评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,772评论 2 339

推荐阅读更多精彩内容