Node.js 连接 MongoDB-7
Posted 慢行厚积
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Node.js 连接 MongoDB-7相关的知识,希望对你有一定的参考价值。
先安装模块:
npm install --save mongodb
当然,首先你要打开mongodb服务端:
mongod --bind_ip 127.0.0.1
创建数据库
要在 MongoDB 中创建一个数据库,首先我们需要创建一个 MongoClient 对象,然后配置好指定的 URL 和 端口号。
如果数据库不存在,MongoDB 将创建数据库并建立连接。
在mongo客户端将mydatabase数据库创建出来:
> show dbs admin 0.000GB config 0.000GB local 0.000GB > use mydatabase switched to db mydatabase > show dbs admin 0.000GB config 0.000GB local 0.000GB >
然后运行:
var MongoClient = require(‘mongodb‘).MongoClient; var url = "mongodb://localhost:27017/mydatabase"; //连接服务端 MongoClient.connect(url, function(err, db) { if (err) throw err; console.log("数据库已创建!"); db.close(); });
返回:
users-MacBook-Pro:test-mongodb user$ node index.js (node:26745) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect. 数据库已创建!
根据上面的警告,将添加相应的option,改为:
MongoClient.connect(url, { useNewUrlParser: true } ,function(err, db) { if (err) throw err; console.log("数据库已创建!"); db.close(); });
返回:
数据库已创建!
创建集合
我们可以使用 createCollection() 方法来创建集合mycollection:
var MongoClient = require(‘mongodb‘).MongoClient; var url = ‘mongodb://localhost:27017/mydatabase‘; MongoClient.connect(url, { useNewUrlParser: true }, function (err, db) { if (err) throw err; console.log(‘数据库已创建‘); var dbase = db.db("mydatabase"); dbase.createCollection(‘mycollection‘, function (err, res) { if (err) throw err; console.log("创建集合!"); db.close(); }); });
返回:
users-MacBook-Pro:test-mongodb user$ node index.js
数据库已创建
创建集合!
客户端查看:
> show collections
mycollection
数据库操作( CURD )
插入数据
以下实例我们连接数据库 mydatabase 的 mycollection 表,并插入一条数据条数据,使用 insertOne():
与 mysql 不同的是 MongoDB 会自动创建数据库和集合,所以使用前我们不需要手动去创建。
var MongoClient = require(‘mongodb‘).MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { if (err) throw err; var dbo = db.db("mydatabase"); var myobj = { name: "菜鸟教程", url: "www.mydatabase" }; dbo.collection("mycollection").insertOne(myobj, function(err, res) { if (err) throw err; console.log("文档插入成功"); db.close(); }); });
返回:
users-MacBook-Pro:test-mongodb user$ node index.js
文档插入成功
客户端查看:
> db.mycollection.find() { "_id" : ObjectId("5c026cae5ae97668886fafaa"), "name" : "菜鸟教程", "url" : "www.mydatabase" }
如果要插入多条数据可以使用 insertMany():
var MongoClient = require(‘mongodb‘).MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { if (err) throw err; var dbo = db.db("mydatabase"); 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("mycollection"). insertMany(myobj, function(err, res) { if (err) throw err; console.log("文档插入成功"); console.log("插入的文档数量为: " + res.insertedCount); db.close(); }); });
返回:
users-MacBook-Pro:test-mongodb user$ node index.js 文档插入成功 插入的文档数量为: 3
客户端查看:
> db.mycollection.find() { "_id" : ObjectId("5c026cae5ae97668886fafaa"), "name" : "菜鸟教程", "url" : "www.mydatabase" } { "_id" : ObjectId("5c026d49ccbd816889e6bb3e"), "name" : "菜鸟工具", "url" : "https://c.runoob.com", "type" : "cn" } { "_id" : ObjectId("5c026d49ccbd816889e6bb3f"), "name" : "Google", "url" : "https://www.google.com", "type" : "en" } { "_id" : ObjectId("5c026d49ccbd816889e6bb40"), "name" : "Facebook", "url" : "https://www.google.com", "type" : "en" }
查询数据
可以使用 find() 来查找数据, find() 可以返回匹配条件的所有数据。 如果未指定条件,find() 返回集合中的所有数据。
var MongoClient = require(‘mongodb‘).MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { if (err) throw err; var dbo = db.db("mydatabase"); dbo.collection("mycollection"). find({}).toArray(function(err, result) { // 返回集合中所有数据 if (err) throw err; console.log(result); db.close(); }); });
返回:
users-MacBook-Pro:test-mongodb user$ node index.js [ { _id: 5c026cae5ae97668886fafaa, name: ‘菜鸟教程‘, url: ‘www.mydatabase‘ }, { _id: 5c026d49ccbd816889e6bb3e, name: ‘菜鸟工具‘, url: ‘https://c.runoob.com‘, type: ‘cn‘ }, { _id: 5c026d49ccbd816889e6bb3f, name: ‘Google‘, url: ‘https://www.google.com‘, type: ‘en‘ }, { _id: 5c026d49ccbd816889e6bb40, name: ‘Facebook‘, url: ‘https://www.google.com‘, type: ‘en‘ } ]
查询指定条件 name 为 "菜鸟教程" 的实例:
var MongoClient = require(‘mongodb‘).MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { if (err) throw err; var dbo = db.db("mydatabase"); var whereStr = {"name":‘菜鸟教程‘}; // 查询条件 dbo.collection("mycollection").find(whereStr).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); });
返回:
users-MacBook-Pro:test-mongodb user$ node index.js [ { _id: 5c026cae5ae97668886fafaa, name: ‘菜鸟教程‘, url: ‘www.mydatabase‘ } ]
更新数据
我们也可以对数据库的数据进行修改,以下实例将 name 为 "菜鸟教程" 的 url 改为 https://www.runoob.com:
var MongoClient = require(‘mongodb‘).MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { if (err) throw err; var dbo = db.db("mydatabase"); var whereStr = {"name":‘菜鸟教程‘}; // 查询条件 var updateStr = {$set: { "url" : "https://www.runoob.com" }}; dbo.collection("mycollection").updateOne(whereStr, updateStr, function(err, res) { if (err) throw err; console.log("文档更新成功"); db.close(); }); });
客户端查看:
> db.mycollection.find() { "_id" : ObjectId("5c026cae5ae97668886fafaa"), "name" : "菜鸟教程", "url" : "https://www.runoob.com" } { "_id" : ObjectId("5c026d49ccbd816889e6bb3e"), "name" : "菜鸟工具", "url" : "https://c.runoob.com", "type" : "cn" } { "_id" : ObjectId("5c026d49ccbd816889e6bb3f"), "name" : "Google", "url" : "https://www.google.com", "type" : "en" } { "_id" : ObjectId("5c026d49ccbd816889e6bb40"), "name" : "Facebook", "url" : "https://www.google.com", "type" : "en" }
如果要更新所有符合条的文档数据可以使用 updateMany():
var MongoClient = require(‘mongodb‘).MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { if (err) throw err; var dbo = db.db("mydatabase"); var whereStr = {"type":‘en‘}; // 查询条件 var updateStr = {$set: { "url" : "https://www.runoob.com" }}; dbo.collection("mycollection").updateMany(whereStr, updateStr, function(err, res) { if (err) throw err; console.log(res.result.nModified + " 条文档被更新"); db.close(); }); });
返回:
users-MacBook-Pro:test-mongodb user$ node index.js 2 条文档被更新
客户端查看:
> db.mycollection.find() { "_id" : ObjectId("5c026cae5ae97668886fafaa"), "name" : "菜鸟教程", "url" : "https://www.runoob.com" } { "_id" : ObjectId("5c026d49ccbd816889e6bb3e"), "name" : "菜鸟工具", "url" : "https://c.runoob.com", "type" : "cn" } { "_id" : ObjectId("5c026d49ccbd816889e6bb3f"), "name" : "Google", "url" : "https://www.runoob.com", "type" : "en" } { "_id" : ObjectId("5c026d49ccbd816889e6bb40"), "name" : "Facebook", "url" : "https://www.runoob.com", "type" : "en" }
删除数据
以下实例将 name 为 "菜鸟教程" 的数据删除 :
var MongoClient = require(‘mongodb‘).MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { if (err) throw err; var dbo = db.db("mydatabase"); var whereStr = {"name":‘菜鸟教程‘}; // 查询条件 dbo.collection("mycollection").deleteOne(whereStr, function(err, obj) { if (err) throw err; console.log("文档删除成功"); db.close(); }); });
返回:
users-MacBook-Pro:test-mongodb user$ node index.js
文档删除成功
客户端查看:
> db.mycollection.find() { "_id" : ObjectId("5c026d49ccbd816889e6bb3e"), "name" : "菜鸟工具", "url" : "https://c.runoob.com", "type" : "cn" } { "_id" : ObjectId("5c026d49ccbd816889e6bb3f"), "name" : "Google", "url" : "https://www.runoob.com", "type" : "en" } { "_id" : ObjectId("5c026d49ccbd816889e6bb40"), "name" : "Facebook", "url" : "https://www.runoob.com", "type" : "en" }
如果要删除多条语句可以使用 deleteMany() 方法
以下实例将 type 为 en 的所有数据删除 :
var MongoClient = require(‘mongodb‘).MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { if (err) throw err; var dbo = db.db("mydatabase"); var whereStr = { type: "en" }; // 查询条件 dbo.collection("mycollection").deleteMany(whereStr, function(err, obj) { if (err) throw err; console.log(obj.result.n + " 条文档被删除"); db.close(); }); });
返回:
users-MacBook-Pro:test-mongodb user$ node index.js 2 条文档被删除
客户端查询:
> db.mycollection.find() { "_id" : ObjectId("5c026d49ccbd816889e6bb3e"), "name" : "菜鸟工具", "url" : "https://c.runoob.com", "type" : "cn" }
排序
排序 使用 sort() 方法,该方法接受一个参数,规定是升序(1)还是降序(-1)。
例如:
{ type: 1 } // 按 type 字段升序 { type: -1 } // 按 type 字段降序
按 type 升序排列:
因为之前删的差不多了,再添加几条:
var MongoClient = require(‘mongodb‘).MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { if (err) throw err; var dbo = db.db("mydatabase"); var myobj = [ { name: ‘菜鸟工具‘, url: ‘https://c.runoob.com‘, type: ‘an‘}, { name: ‘Google‘, url: ‘https://www.google.com‘, type: ‘bn‘}, { name: ‘Facebook‘, url: ‘https://www.google.com‘, type: ‘dn‘} ]; dbo.collection("mycollection"). insertMany(myobj, function(err, res) { if (err) throw err; console.log("文档插入成功"); console.log("插入的文档数量为: " + res.insertedCount); db.close(); }); });
客户端:
> db.mycollection.find() { "_id" : ObjectId("5c026d49ccbd816889e6bb3e"), "name" : "菜鸟工具", "url" : "https://c.runoob.com", "type" : "cn" } { "_id" : ObjectId("5c0270aad64fbc6896311aac"), "name" : "菜鸟工具", "url" : "https://c.runoob.com", "type" : "an" } { "_id" : ObjectId("5c0270aad64fbc6896311aad"), "name" : "Google", "url" : "https://www.google.com", "type" : "bn" } { "_id" : ObjectId("5c0270aad64fbc6896311aae"), "name" : "Facebook", "url" : "https://www.google.com", "type" : "dn" }
然后排序:
var MongoClient = require(‘mongodb‘).MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { if (err) throw err; var dbo = db.db("mydatabase"); var mysort = { type: 1 }; dbo.collection("mycollection").find().sort(mysort).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); });
返回:
users-MacBook-Pro:test-mongodb user$ node index.js [ { _id: 5c0270aad64fbc6896311aac, name: ‘菜鸟工具‘, url: ‘https://c.runoob.com‘, type: ‘an‘ }, { _id: 5c0270aad64fbc6896311aad, name: ‘Google‘, url: ‘https://www.google.com‘, type: ‘bn‘ }, { _id: 5c026d49ccbd816889e6bb3e, name: ‘菜鸟工具‘, url: ‘https://c.runoob.com‘, type: ‘cn‘ }, { _id: 5c0270aad64fbc6896311aae, name: ‘Facebook‘, url: ‘https://www.google.com‘, type: ‘dn‘ } ]
查询分页
首先客户端查看得到现在的存储状态:
> db.mycollection.find() { "_id" : ObjectId("5c026d49ccbd816889e6bb3e"), "name" : "菜鸟工具", "url" : "https://c.runoob.com", "type" : "cn" } { "_id" : ObjectId("5c0270aad64fbc6896311aac"), "name" : "菜鸟工具", "url" : "https://c.runoob.com", "type" : "an" } { "_id" : ObjectId("5c0270aad64fbc6896311aad"), "name" : "Google", "url" : "https://www.google.com", "type" : "bn" } { "_id" : ObjectId("5c0270aad64fbc6896311aae"), "name" : "Facebook", "url" : "https://www.google.com", "type" : "dn" }
如果要设置指定的返回条数可以使用 limit() 方法,该方法只接受一个参数,指定了返回的条数。
var MongoClient = require(‘mongodb‘).MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { if (err) throw err; var dbo = db.db("mydatabase"); dbo.collection("mycollection").find().limit(2).toArray(function(err, result) {//只得到前两条数据 if (err) throw err; console.log(result); db.close(); }); });
返回:
users-MacBook-Pro:test-mongodb user$ node index.js [ { _id: 5c026d49ccbd816889e6bb3e, name: ‘菜鸟工具‘, url: ‘https://c.runoob.com‘, type: ‘cn‘ }, { _id: 5c0270aad64fbc6896311aac, name: ‘菜鸟工具‘, url: ‘https://c.runoob.com‘, type: ‘an‘ } ]
如果要指定跳过的条数,可以使用 skip() 方法。
var MongoClient = require(‘mongodb‘).MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { if (err) throw err; var dbo = db.db("mydatabase"); dbo.collection("mycollection").find().skip(2).limit(2).toArray(function(err, result) {//跳过前两条数据,只得到后两条数据 if (err) throw err; console.log(result); db.close(); }); });
返回:
users-MacBook-Pro:test-mongodb user$ node index.js [ { _id: 5c0270aad64fbc6896311aad, name: ‘Google‘, url: ‘https://www.google.com‘, type: ‘bn‘ }, { _id: 5c0270aad64fbc6896311aae, name: ‘Facebook‘, url: ‘https://www.google.com‘, type: ‘dn‘ } ]
连接操作
mongoDB 不是一个关系型数据库,但我们可以使用 $lookup 来实现左连接。
例如我们有两个集合数据分别为:
先创建相应的集合:
集合1:orders
var MongoClient = require(‘mongodb‘).MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { if (err) throw err; var dbo = db.db("mydatabase"); var myobj = { _id: 1, product_id: 154, status: 1 }; dbo.collection("orders").insertOne(myobj, function(err, res) { if (err) throw err; console.log("文档插入成功"); db.close(); }); });
客户端查看:
> db.orders.find() { "_id" : 1, "product_id" : 154, "status" : 1 }
集合2:products
var MongoClient = require(‘mongodb‘).MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { if (err) throw err; var dbo = db.db("mydatabase"); var myobj = [ { _id: 154, name: ‘笔记本电脑‘ }, { _id: 155, name: ‘耳机‘ }, { _id: 156, name: ‘台式电脑‘ } ]; dbo.collection("products"). insertMany(myobj, function(err, res) { if (err) throw err; console.log("文档插入成功"); console.log("插入的文档数量为: " + res.insertedCount); db.close(); }); });
客户端查看:
> db.products.find() { "_id" : 154, "name" : "笔记本电脑" } { "_id" : 155, "name" : "耳机" } { "_id" : 156, "name" : "台式电脑" } >
实现左连接:
var MongoClient = require(‘mongodb‘).MongoClient; var url = "mongodb://127.0.0.1:27017/"; MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { if (err) throw err; var dbo = db.db("mydatabase"); 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(); }); });
返回:
users-MacBook-Pro:test-mongodb user$ node index.js [{"_id":1,"product_id":154,"status":1,"orderdetails":[{"_id":154,"name":"笔记本电脑"}]}]
即orders集合字段"product_id" : 154与products的_id相符合的products的数据将会为字段orderdetails的值,并存放到orders的数据内,然后返回一个值
删除集合
我们可以使用 drop() 方法来删除集合:
var MongoClient = require(‘mongodb‘).MongoClient; var url = "mongodb://127.0.0.1:27017/"; MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { if (err) throw err; var dbo = db.db("mydatabase"); dbo.collection("products").drop(function(err, delOK) { // 执行成功 delOK 返回 true,否则返回 false if (err) throw err; if (delOK) console.log("集合已删除"); db.close(); }); });
客户端查询:
> db.products.find()
>
以上是关于Node.js 连接 MongoDB-7的主要内容,如果未能解决你的问题,请参考以下文章
为啥建议不要在 Node.js 代码的任何地方关闭 MongoDB 连接?
为啥建议不要在 Node.js 代码的任何地方关闭 MongoDB 连接?