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 .000GB
config .000GB
local .000GB
> use mydatabase
switched to db mydatabase
> show dbs
admin .000GB
config .000GB
local .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:) 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
文档插入成功
插入的文档数量为:
客户端查看:
> 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
条文档被更新
客户端查看:
> 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
条文档被删除
客户端查询:
> db.mycollection.find()
{ "_id" : ObjectId("5c026d49ccbd816889e6bb3e"), "name" : "菜鸟工具", "url" : "https://c.runoob.com", "type" : "cn" }
排序
排序 使用 sort() 方法,该方法接受一个参数,规定是升序(1)还是降序(-1)。
例如:
{ type: } // 按 type 字段升序
{ type: - } // 按 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: };
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().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().limit().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: , product_id: , status: };
dbo.collection("orders").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("文档插入成功");
db.close();
});
});
客户端查看:
> db.orders.find()
{ "_id" : , "product_id" : , "status" : }
集合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: , name: '笔记本电脑' },
{ _id: , name: '耳机' },
{ _id: , 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" : , "name" : "笔记本电脑" }
{ "_id" : , "name" : "耳机" }
{ "_id" : , "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":,"product_id":,"status":,"orderdetails":[{"_id":,"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操作mysql以及redis的内容,这里继续学习操作mongodb的内容. 安装驱动 安装命令 cnpm install mongodb 安装成功 数据库操作 因为mon ...
- windows下安装mongodb以及node.js连接mongodb
一.MongoDB 下载 下载地址 https://www.mongodb.com/download-center#community 选择windows版下载,然后安装. 二.安装完毕后创建数据 ...
- Node.js连接MongoDB数据库
首先要启动MongoDB服务器 先找到你的mongoDb安装目录,我的如下:就在bin文件夹下创建一个data文件夹,data内包含两个空文件夹,如下: 接着回到bin文件夹处,按住shift键,右击 ...
- node.js连接MongoDB数据库,db.collection is not a function完美解决
解决方法一. mongodb数据库版本回退: 这个错误是出在mongodb的库中,在nodejs里的写法和命令行中的写法不一样,3.0的api已经更新和以前的版本不不一样,我们在npm中没指定版本号的 ...
- Node.js 连接 MongoDB数据库
安装指令:npm install mongodb var mongodb = require("mongodb");// console.log(mongodb); var Mon ...
- Node.js连接MongoDB
使用monk访问mongodb mongodb.monk都安装了依赖的前提下: 首先启动MongoDB 服务:mongod: 进入了mongodb后台管理,再通过终端创建数据库:use monk-ap ...
- 初学node.js-nodejs连接MongoDB(5)
一.吧MongoDB的驱动程序添加到Node.js中 Node.js 连接 MongoDB 连接
- Node.js向MongoDB中插入并查询数据
首先必须要保持Node.js与MongoDB保持连接 具体教程见:Node.js连接MongoDB数据库步骤 插入数据步骤如下 node项目文件如下:在routes文件夹下新建insert.js文件, ...
- Node.js和MongoDB - MongoJS入门
第一次尝试翻译外国牛人的博文,希望大家喜欢. 本文源码详见:https://github.com/njaulj/mongojs 一点都不夸大的说,近年来node.js和mongodb的确是大放异彩,在 ...
- node.js连接MySQL操作及注意事项
node.js作为服务端的js运行环境已经出现了有几年了,最近我有个朋友也在做这方面的开发,但是也是刚刚接触,遇到了很多坑.前几天他们在操作数据库的时候出现了点问题,后来我们一起看了看,其实都是nod ...
随机推荐
- elasticsearch 6.3 安装手记
系统环境 centos 7 elasticsearch 6.3 需要 JDK 8 版本,先安装 JDK 8. ES6.3 安装地址: https://www.elastic.co/guide/en/e ...
- vue.js 项目打包
vuejs是个前端框架,npm run dev的目的在于前端开发的时候可以实时调试.所以npm run dev 只是开发时期会用到,在生产环境中我们应该使用nginx,apahce tomcat等应用 ...
- cf444E. DZY Loves Planting(并查集)
题意 题目链接 Sol 神仙题啊Orzzzzzz 考场上的时候直接把树扔了对着式子想,想1h都没得到啥有用的结论. 然后cf正解居然是网络流??出给NOIP模拟赛T1???¥%--&((--% ...
- java.lang.IllegalStateException: Mapped class was not specified
错误如下:java.lang.IllegalStateException: Mapped class was not specifiedat org.springframework.util.Asse ...
- freecodecamp 基础算法题笔记
数组与字符串的转化 字符串转化成数组 reverse方法翻转数组顺序 数组转化成字符串. function reverseString(str) { a= str.split("" ...
- angular自定义指令 repeat 循环结束事件;limitTo限制循环长度、限定开始位置
1.获取repeat循环结束: 自定义指令: .directive('repeatFinish', function () { return { link: function (scope, elem ...
- Anaconda多环境多版本python配置笔记
一.Conda测试过程: 使用conda.首先确认已经安装好了conda 配置环境.下一步通过创建几个环境来展示conda的环境管理功能.学习如何确认在哪个环境中,以及如何做复制一个环境作为备份. 测 ...
- hibernate、java、数据库对应类型
引自 https://my.oschina.net/heau/blog/498874 java.数据库对应类型 类型名称 显示长度 数据库类型 JAVA类型 JDBC类型索引(int) 描述 ...
- ios 下拉列表
#import <UIKit/UIKit.h> @class FVPullDownMenu; /** 指示器状态*/ typedef enum { IndicatorStateShow = ...
- Spring Boot—11控制器Controller
package com.sample.smartmap.controller; import org.springframework.beans.factory.annotation.Autowire ...