Nodejs操作MongoDB数据库增删改查及性能测试

本文详细介绍使用Node.js操作MongoDB数据库的方法,包括数据库连接、基本的增删改查操作及性能测试技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Node.js操作MongoDB数据的步骤

官方文档:http://mongodb.github.io/node-mongodb-native/3.1/quick-start/quick-start/

  • 安装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');

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值