操作Mongodb数据库,性能测试
-
目标:基于官方的node-mongodb-natice驱动,封装一个更小、更快、更灵活的DB模块,让我们用nodejs操作Mongodb数据库更方便、更灵活。
引入mongodb模板
cnpm install mongodb --save
开启mongodb数据库
sudo mongod
...
mongo
连接mongodb数据库
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'koa';
// Create a new MongoClient
const client = new MongoClient(url);
// Use connect method to connect to the Server
client.connect(function(err) {
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
插入一条数据
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'koa';
// Create a new MongoClient
const client = new MongoClient(url, { useUnifiedTopology: true });
// Use connect method to connect to the Server
client.connect(function(err) {
console.log("Connected successfully to server");
const db = client.db(dbName);
db.collection('user').insertOne({ 'username': '阿牛111', 'age': 11, 'sex': '男', 'status': 1 }, function(err, result) {
if (err) {
console.log(err);
} else {
console.log('增加数据成功');
}
client.close();
})
});
查询全部数据
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'koa';
// Create a new MongoClient
const client = new MongoClient(url, { useUnifiedTopology: true });
// Use connect method to connect to the Server
client.connect(function(err) {
console.log("Connected successfully to server");
const db = client.db(dbName);
db.collection('user').find({}).toArray(function(err, docs) {
console.log("Found the following records");
console.log(docs)
});
});
测试性能
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'koa';
// Create a new MongoClient
const client = new MongoClient(url, { useUnifiedTopology: true });
console.time('start');
// Use connect method to connect to the Server
client.connect(function(err) {
console.log("Connected successfully to server");
const db = client.db(dbName);
db.collection('user').insertOne({ 'username': '阿牛444', 'age': 44, 'sex': '男', 'status': 1 }, function(err, result) {
if (err) {
console.log(err);
} else {
console.log('增加数据成功');
}
client.close();
console.timeEnd('start');
})
});