概述
原生nodejs操作mongoDB
通过 mongoDB下的 MongoClient 实现
官网API地址
版本3.3;由于版本更迭,语法也是有区别的
在OPTIONS 中通过 Select Version 切换版本,查看对应语法
快速使用
1.初始化项目与安装
mkdir myproject
cd myproject
npm init
npm install mongodb --save
2.创建一个目录,作为mongoDB的存储位置,并且启动数据库(不能关闭此命令窗口)
mongod --dbpath '数据存储路径'
3.连接已经开启的数据库
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert'); //node内置模块断言,简化err逻辑的判断书写
const url = 'mongodb://localhost:27017'; //通过第2步,开启数据库的 log中,查看连接的位置
const dbName = '数据库名';
const client = new MongoClient(url);
client.connect(function(err) {
assert.equal(null, err);
const db = client.db(dbName);
.....增删改查业务逻辑....
console.log('数据库已经连接');
client.close();
});
4.核心业务逻辑部分 【增】
const collection = db.collection('库中的表名');
//--插入一条
collection.insertOne({a : 1}, function(err, result) {
assert.equal(err, null);
console.log("Inserted 1 documents into the collection");
callback(result);
});
//--插入多条
collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) {
assert.equal(err, null);
console.log("Inserted 3 documents into the collection");
callback(result);
});
5.核心业务逻辑部分 【查】
const collection = db.collection('库中的表名');
//--查询所有数据
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
callback(docs);
});
//--筛选查询数据
collection.find({'name':'zhangsan'}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
callback(docs);
});
6.核心业务逻辑部分 【改】
const collection = db.collection('库中的表名');
//--为张三设置或者更新年龄18
collection.updateOne({ 'name' : 'zhangsan' }
, { $set: { 'age' : 18 } }, function(err, result) {
assert.equal(err, null);
console.log("Updated the document");
callback(result);
});
7.核心业务逻辑部分 【删】
const collection = db.collection('库中的表名');
//--删除名字为张三的数据,且只删除发现的第一条
collection.deleteOne({ 'name' : 'zhangsan' }, function(err, result) {
assert.equal(err, null);
console.log("Removed the document");
callback(result);
});
8.核心业务逻辑部分 【设置索引】
const collection = db.collection('库中的表名');
//--为name增加索引,提升查询name的速度
db.collection('documents').createIndex(
{ "name": 1 },
null,
function(err, results) {
console.log(results);
callback();
}
)};
网友评论