第一章 Native Driver
1 安装
npm install mongodb --save
2 连接 MongoDB 服务
2.1 连接不需要登录验证的 MongoDB 服务
//导入模块
const MongoClient = require('mongodb').MongoClient;
// 定义 连接url
const url = 'mongodb://localhost:27017';
// 定义数据库
const dbName = 'myproject';
// 连接MongoDB服务器
MongoClient.connect(url, function(err, client) {
if (err) throw err;
//选择数据库
const db = client.db(dbName);
client.close();
});
2.2 连接需要登录验证的 MongoDB 服务
//导入模块
const MongoClient = require('mongodb').MongoClient;
const util = require('util');
//声明用户名 密码
const user = encodeURIComponent('dave');
const password = encodeURIComponent('abc123');
// 定义 URL
const url = util.format('mongodb://%s:%s@localhost:27017/',
user, password);
// 连接服务
MongoClient.connect(url, function(err, client) {
if (err) throw err;
//选择数据库
const db = client.db(dbName);
client.close();
});
3 集合操作
3.1 创建集合
db.createCollection(coolName, { "capped": true, "size": 100000, "max": 5000},
function(err, results) {
if (err) throw err;
//results 是表示集合的对象
console.log("集合创建成功.");
}
);
3.2 删除集合
db.dropCollection(coolName, (err, result) => {
if (err) throw err;
console.log('删除成功');
})
4 CURD 增删改查 (Create Update Retrieve Delete)
4.1 添加文档
// 添加一条文档
db.collection('collName').insertOne({a:1}, function(err, r) {
if (err) throw err;
console.log(r.insertedCount);
});
// 添加多条文档
db.collection('collName').insertMany([{a:2}, {a:3}], function(err, r) {
if (err) throw err;
console.log(r.insertedCount);
});
不温馨地提示:MongoDB 会自动创建集合。
4.2 更新文档
const col = db.collection('collName');
// 更新一条文档
col.updateOne({a:3}, {$set: {b: 1}}, {
upsert: true
}, function(err, r) {
if (err) throw err;
console.log(r.matchedCount);
console.log(r.upsertedCount);
});
// 更新多条文档
col.updateMany({a:2}, {$set: {b: 1}}, function(err, r) {
if (err) throw err;
console.log(r.matchedCount);
console.log(r.modifiedCount);
})
4.3 删除文档
const col = db.collection('collName');
// 删除一条文档
col.deleteOne({a:1}, function(err, r) {
if (err) throw err;
console.log(r.deletedCount);
});
// 删除多条文档
col.deleteMany({a:2}, function(err, r) {
if(err) throw err;
console.log(r.deletedCount);
});
4.4 查询文档
const col = db.collection('collName');
// 查询满足条件的一条数据
col.findOne({a:100}, function(err, result) { // 返回集合中所有数据
if (err) throw err;
console.log(result);
});
// 查询满足条件的所有数据
col.find({}).toArray(function(err, result) { // 返回集合中所有数据
if (err) throw err;
console.log(result);
});
// 查询并修改
col.findOneAndUpdate({a:1}, {$set: {b: 1}}, {
returnOriginal: false
, sort: [[a,1]]
, upsert: true
}, function(err, r) {
if (err) throw err;
console.log(r.value); //r.value是修改前的文档
})
// 查询并且删除
col.findOneAndDelete({a:2}, function(err, r) {
if (err) throw err;
console.log(r.value); //返回被删掉的文档
});
// 排序
col.find().sort().toArray()
// 数量限制
col.find().skip().limit().toArray()
col.find().limit().toArray()