1. 程式人生 > >Nodejs操作MongoDB資料庫增刪改查及效能測試

Nodejs操作MongoDB資料庫增刪改查及效能測試

1.Node.js操作MongoDB資料的步驟

  • 安裝MongoDB
mkdir koaMongodb
cd koaMongodb
npm init
npm install mongodb --save
  • 引入MongoDB下面的MongoDBClient
 var MongoClient = require('mongodb').MongoClient;
  • 定義資料庫連線的地址已經配置資料庫
koa資料庫的名稱

    var url = 'mongodb://localhost:27017/';

    var dbName = 'koa'
  • Node.js連線資料庫
 MongoClient.connect(url,function(err,client){

        const db = client.db(dbName);  資料庫db物件

 })
  • 操作資料庫(插入示例)
  db.user.insert
     MongoClient.connect(url,function(err,db){
            db.collection('user').insertOne({"name":"張三"},function(err,result){

                db.close() //關閉連線
            })
     })

2.Node.js操作MongoDB進行增刪改查操作

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://193.112.168.19:27017';

// Database Name
const dbName = 'koa';
console.time('start');
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
    assert.equal(null, err);
    console.log("MongoDB server Connected successfully to server");
    const db = client.db(dbName);

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

            });
        });
    })
});

const insertDocuments = function(db, callback) {
    // Get the documents collection
    const collection = db.collection('user');
    // Insert some documents
    collection.insertMany([
        {username : "hemeili"   ,age : "22",sex : "女" , status : "0" },
        {username : "doujinmin" ,age : "32",sex : "男" , status : "1" },
        {username : "yanghexing",age : "19",sex : "女" , status : "0" },
    ], 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);
    });
};

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

const removeDocument = function(db, callback) {
    // Get the documents collection
    const collection = db.collection('user');
    // Delete document where a is 3
    collection.deleteOne({ 'username': 'hemeili' }, 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);
    });
};

const updateDocument = function(db, callback) {
    // Get the documents collection
    const collection = db.collection('user');
    // Update document where a is 2, set b equal to 1
    collection.updateOne({ 'username': 'lisi' }
        , { $set: { 'sex' : '女' } }, function(err, result) {
            assert.equal(err, null);
            assert.equal(1, result.result.n);
            console.timeEnd('start');
            console.log("Updated the document with the field a equal to 2");
            callback(result);
        });
};

3.效能測試

通過以下兩行程式碼測試程式碼執行時間,進而分析測試效能。

console.time('start');

console.timeEnd('start');