查看“Node.js:MongoDB”的源代码
←
Node.js:MongoDB
跳到导航
跳到搜索
因为以下原因,您没有权限编辑本页:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
[[category:Node.js教程]] == 关于 == <syntaxhighlight lang="bash" highlight=""> MongoDB 是一种文档导向数据库管理系统,由 C++ 撰写而成。 </syntaxhighlight> Node.js 连接 MongoDB,并对数据库进行操作。 == 安装驱动 == 使用了 cnpm 命令(淘宝定制的命令)进行安装: <syntaxhighlight lang="bash" highlight=""> $ cnpm install mongodb </syntaxhighlight> == 创建数据库 == 要在 MongoDB 中创建一个数据库,首先我们需要创建一个 '''MongoClient''' 对象,然后配置好指定的 URL 和 端口号。 * 如果数据库不存在,MongoDB 将创建数据库并建立连接。 示例:创建连接 <syntaxhighlight lang="JavaScript" highlight=""> var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/runoob"; MongoClient.connect(url, function(err, db) { if (err) throw err; console.log("数据库已创建!"); db.close(); }); </syntaxhighlight> == 创建集合 == 可以使用 createCollection() 方法来创建集合: <syntaxhighlight lang="JavaScript" highlight=""> var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost:27017/runoob'; MongoClient.connect(url, function (err, db) { if (err) throw err; console.log('数据库已创建'); var dbase = db.db("runoob"); dbase.createCollection('site', function (err, res) { if (err) throw err; console.log("创建集合!"); db.close(); }); }); </syntaxhighlight> == 数据库操作( CURD ) == 与 MySQL 不同的是 MongoDB 会'''自动创建数据库和集合''',所以使用前我们不需要手动去创建。 === 查询数据 === '''find()''':查找数据。 * find() 可以返回匹配条件的所有数据。 * 如果未指定条件,find() 返回集合中的所有数据。 示例 1:检索所有数据 <syntaxhighlight lang="JavaScript" highlight=""> var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("runoob"); dbo.collection("site"). find({}).toArray(function(err, result) { // 返回集合中所有数据 if (err) throw err; console.log(result); db.close(); }); }); </syntaxhighlight> 示例 2:检索 name 为 "菜鸟教程" 的数据 <syntaxhighlight lang="JavaScript" highlight=""> var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("runoob"); var whereStr = {"name":'菜鸟教程'}; // 查询条件 dbo.collection("site").find(whereStr).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); }); </syntaxhighlight> 执行结果: <syntaxhighlight lang="bash" highlight=""> [ { _id: 5a794e36763eb821b24db854, name: '菜鸟教程', url: 'www.runoob' } ] </syntaxhighlight> === 插入数据 === # '''insertOne()''':插入一条数据。 # '''insertMany()''':插入多条数据。 示例 1:连接数据库 runoob 的 site 表,并插入一条数据条数据: <syntaxhighlight lang="JavaScript" highlight=""> var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("runoob"); var myobj = { name: "菜鸟教程", url: "www.runoob" }; dbo.collection("site").insertOne(myobj, function(err, res) { if (err) throw err; console.log("文档插入成功"); db.close(); }); }); </syntaxhighlight> 执行结果: <syntaxhighlight lang="bash" highlight=""> $ node test.js 文档插入成功 </syntaxhighlight> 打开 MongoDB 的客户端查看数据,如: <syntaxhighlight lang="bash" highlight=""> > show dbs runoob 0.000GB # 自动创建了 runoob 数据库 > show tables site # 自动创建了 site 集合(数据表) > db.site.find() { "_id" : ObjectId("5a794e36763eb821b24db854"), "name" : "菜鸟教程", "url" : "www.runoob" } > </syntaxhighlight> 示例 2:连接数据库 runoob 的 site 表,并插入一条数据条数据: <syntaxhighlight lang="JavaScript" highlight=""> var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("runoob"); var myobj = [ { name: '菜鸟工具', url: 'https://c.runoob.com', type: 'cn'}, { name: 'Google', url: 'https://www.google.com', type: 'en'}, { name: 'Facebook', url: 'https://www.google.com', type: 'en'} ]; dbo.collection("site").insertMany(myobj, function(err, res) { if (err) throw err; console.log("插入的文档数量为: " + res.insertedCount); db.close(); }); }); </syntaxhighlight> 其中:res.insertedCount 为插入的条数。 === 更新数据 === # '''updateOne()''':更改单条文档数据; # '''updateMany()''':更新所有符合条的文档数据; 示例 1:将 name 为 "菜鸟教程" 的 url 改为 <nowiki>https://www.runoob.com</nowiki>: <syntaxhighlight lang="JavaScript" highlight=""> var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("runoob"); var whereStr = {"name":'菜鸟教程'}; // 查询条件 var updateStr = {$set: { "url" : "https://www.runoob.com" }}; dbo.collection("site").updateOne(whereStr, updateStr, function(err, res) { if (err) throw err; console.log("文档更新成功"); db.close(); }); }); </syntaxhighlight> 进入 mongo 管理工具查看数据已修改: <syntaxhighlight lang="bash" highlight=""> > db.site.find().pretty() { "_id" : ObjectId("5a794e36763eb821b24db854"), "name" : "菜鸟教程", "url" : "https://www.runoob.com" // 已修改为 https } </syntaxhighlight> 示例 2:更新所有符合条的文档数据 <syntaxhighlight lang="JavaScript" highlight=""> var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("runoob"); var whereStr = {"type":'en'}; // 查询条件 var updateStr = {$set: { "url" : "https://www.runoob.com" }}; dbo.collection("site").updateMany(whereStr, updateStr, function(err, res) { if (err) throw err; console.log(res.result.nModified + " 条文档被更新"); db.close(); }); }); </syntaxhighlight> 其中:result.nModified 为更新的条数。 === 删除数据 === # '''deleteOne()''':删除单条文档数据; # '''deleteMany()''':删除所有符合条的文档数据; 示例 1:将 name 为 "菜鸟教程" 的数据删除 <syntaxhighlight lang="JavaScript" highlight=""> var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("runoob"); var whereStr = {"name":'菜鸟教程'}; // 查询条件 dbo.collection("site").deleteOne(whereStr, function(err, obj) { if (err) throw err; console.log("文档删除成功"); db.close(); }); }); </syntaxhighlight> 进入 mongo 管理工具查看数据已删除: <syntaxhighlight lang="bash" highlight=""> > db.site.find() > </syntaxhighlight> 示例 2:将 type 为 en 的所有数据删除 <syntaxhighlight lang="JavaScript" highlight=""> var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("runoob"); var whereStr = { type: "en" }; // 查询条件 dbo.collection("site").deleteMany(whereStr, function(err, obj) { if (err) throw err; console.log(obj.result.n + " 条文档被删除"); db.close(); }); }); </syntaxhighlight> 其中:obj.result.n 为删除的条数。 === 排序 === 排序使用 '''sort()''' 方法,该方法接受一个参数,规定是升序/降序: <syntaxhighlight lang="JavaScript" highlight=""> { type: 1 } // 按 type 字段升序 { type: -1 } // 按 type 字段降序 </syntaxhighlight> 示例:按 type 升序排列 <syntaxhighlight lang="JavaScript" highlight=""> var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("runoob"); var mysort = { type: 1 }; dbo.collection("site").find().sort(mysort).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); }); </syntaxhighlight> === 查询分页 === # '''limit()'''方法:设置指定的返回条数,该方法只接受一个参数,指定了返回的条数; # '''skip()'''方法:指定跳过的条数; 示例 1:读取两条数据 <syntaxhighlight lang="JavaScript" highlight=""> var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("runoob"); dbo.collection("site").find().limit(2).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); }); </syntaxhighlight> 示例 2:跳过前面两条数据,读取两条数据 <syntaxhighlight lang="JavaScript" highlight=""> var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("runoob"); dbo.collection("site").find().skip(2).limit(2).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); }); </syntaxhighlight> === 连接操作 === mongoDB 不是一个关系型数据库,但我们可以使用 '''$lookup''' 来实现'''左连接'''。 示例:例如我们有两个集合数据分别为: 集合1:orders <syntaxhighlight lang="bash" highlight=""> [ { _id: 1, product_id: 154, status: 1 } ] </syntaxhighlight> 集合2:products <syntaxhighlight lang="bash" highlight=""> [ { _id: 154, name: '笔记本电脑' }, { _id: 155, name: '耳机' }, { _id: 156, name: '台式电脑' } ] </syntaxhighlight> 实现左连接: <syntaxhighlight lang="JavaScript" highlight=""> var MongoClient = require('mongodb').MongoClient; var url = "mongodb://127.0.0.1:27017/"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("runoob"); dbo.collection('orders').aggregate([ { $lookup: { from: 'products', // 右集合 localField: 'product_id', // 左集合 join 字段 foreignField: '_id', // 右集合 join 字段 as: 'orderdetails' // 新生成字段(类型array) } } ]).toArray(function(err, res) { if (err) throw err; console.log(JSON.stringify(res)); db.close(); }); }); </syntaxhighlight> === 删除集合 === '''drop()''' 方法删除集合。 示例: <syntaxhighlight lang="JavaScript" highlight=""> var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("runoob"); // 删除 test 集合 dbo.collection("test").drop(function(err, delOK) { // 执行成功 delOK 返回 true,否则返回 false if (err) throw err; if (delOK) console.log("集合已删除"); db.close(); }); }); </syntaxhighlight> == 使用 Promise == '''Promise''' 是一个 ECMAScript 6 提供的类,目的是更加优雅地'''书写复杂的异步任务'''。 * 参考:[https://www.runoob.com/js/js-promise.html JavaScript Promise]。 === Promise 创建集合 === 示例: <syntaxhighlight lang="JavaScript" highlight=""> const MongoClient = require("mongodb").MongoClient; const url = "mongodb://localhost/runoob"; MongoClient.connect(url).then((conn) => { console.log("数据库已连接"); var dbase = conn.db("runoob"); dbase.createCollection("site").then((res) => { console.log("已创建集合"); }).catch((err) => { console.log("数据库操作错误"); }).finally(() => { conn.close(); }); }).catch((err) => { console.log("数据库连接失败"); }); </syntaxhighlight> === Promise 数据操作 === 示例:在一个程序中实现四个连续操作:增加 、查询 、更改 、删除。 <syntaxhighlight lang="JavaScript" highlight=""> const MongoClient = require("mongodb").MongoClient; const url = "mongodb://localhost/"; MongoClient.connect(url).then((conn) => { console.log("数据库已连接"); const test = conn.db("testdb").collection("test"); // 增加 test.insertOne({ "site": "runoob.com" }).then((res) => { // 查询 return test.find().toArray().then((arr) => { console.log(arr); }); }).then(() => { // 更改 return test.updateMany({ "site": "runoob.com" }, { $set: { "site": "example.com" } }); }).then((res) => { // 查询 return test.find().toArray().then((arr) => { console.log(arr); }); }).then(() => { // 删除 return test.deleteMany({ "site": "example.com" }); }).then((res) => { // 查询 return test.find().toArray().then((arr) => { console.log(arr); }); }).catch((err) => { console.log("数据操作失败" + err.message); }).finally(() => { conn.close(); }); }).catch((err) => { console.log("数据库连接失败"); }); </syntaxhighlight> 进入 mongo 管理工具查看数据: <syntaxhighlight lang="bash" highlight=""> 数据库已连接 [ { _id: 5f1664966833e531d83d3ac6, site: 'runoob.com' } ] [ { _id: 5f1664966833e531d83d3ac6, site: 'example.com' } ] [] </syntaxhighlight> 用异步函数实现相同的数据操作: <syntaxhighlight lang="JavaScript" highlight=""> const MongoClient = require("mongodb").MongoClient; const url = "mongodb://localhost/"; async function dataOperate() { var conn = null; try { conn = await MongoClient.connect(url); console.log("数据库已连接"); const test = conn.db("testdb").collection("test"); // 增加 await test.insertOne({ "site": "runoob.com" }); // 查询 var arr = await test.find().toArray(); console.log(arr); // 更改 await test.updateMany({ "site": "runoob.com" }, { $set: { "site": "example.com" } }); // 查询 arr = await test.find().toArray(); console.log(arr); // 删除 await test.deleteMany({ "site": "example.com" }); // 查询 arr = await test.find().toArray(); console.log(arr); } catch (err) { console.log("错误:" + err.message); } finally { if (conn != null) conn.close(); } } dataOperate(); </syntaxhighlight> 进入 mongo 管理工具查看数据: <syntaxhighlight lang="bash" highlight=""> 数据库已连接 [ { _id: 5f169006a2780f0cd4ea640b, site: 'runoob.com' } ] [ { _id: 5f169006a2780f0cd4ea640b, site: 'example.com' } ] [] </syntaxhighlight> 运行结果完全一样。 很显然,异步函数是一种非常良好的编程风格,在多次使用异步操作的时候非常实用。 * 但是请勿在低于 7.6.0 版本的 node.js 上使用异步函数。
返回至“
Node.js:MongoDB
”。
导航菜单
个人工具
登录
命名空间
页面
讨论
大陆简体
已展开
已折叠
查看
阅读
查看源代码
查看历史
更多
已展开
已折叠
搜索
导航
首页
最近更改
随机页面
MediaWiki帮助
笔记
服务器
数据库
后端
前端
工具
《To do list》
日常
阅读
电影
摄影
其他
Software
Windows
WIKIOE
所有分类
所有页面
侧边栏
站点日志
工具
链入页面
相关更改
特殊页面
页面信息