先安装模块:

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的更多相关文章

  1. [Node.js]连接mongodb

    摘要 前面介绍了node.js操作mysql以及redis的内容,这里继续学习操作mongodb的内容. 安装驱动 安装命令 cnpm install mongodb 安装成功 数据库操作 因为mon ...

  2. windows下安装mongodb以及node.js连接mongodb

    一.MongoDB 下载 下载地址  https://www.mongodb.com/download-center#community  选择windows版下载,然后安装. 二.安装完毕后创建数据 ...

  3. Node.js连接MongoDB数据库

    首先要启动MongoDB服务器 先找到你的mongoDb安装目录,我的如下:就在bin文件夹下创建一个data文件夹,data内包含两个空文件夹,如下: 接着回到bin文件夹处,按住shift键,右击 ...

  4. node.js连接MongoDB数据库,db.collection is not a function完美解决

    解决方法一. mongodb数据库版本回退: 这个错误是出在mongodb的库中,在nodejs里的写法和命令行中的写法不一样,3.0的api已经更新和以前的版本不不一样,我们在npm中没指定版本号的 ...

  5. Node.js 连接 MongoDB数据库

    安装指令:npm install mongodb var mongodb = require("mongodb");// console.log(mongodb); var Mon ...

  6. Node.js连接MongoDB

    使用monk访问mongodb mongodb.monk都安装了依赖的前提下: 首先启动MongoDB 服务:mongod: 进入了mongodb后台管理,再通过终端创建数据库:use monk-ap ...

  7. 初学node.js-nodejs连接MongoDB(5)

    一.吧MongoDB的驱动程序添加到Node.js中 Node.js 连接 MongoDB 连接

  8. Node.js向MongoDB中插入并查询数据

    首先必须要保持Node.js与MongoDB保持连接 具体教程见:Node.js连接MongoDB数据库步骤 插入数据步骤如下 node项目文件如下:在routes文件夹下新建insert.js文件, ...

  9. Node.js和MongoDB - MongoJS入门

    第一次尝试翻译外国牛人的博文,希望大家喜欢. 本文源码详见:https://github.com/njaulj/mongojs 一点都不夸大的说,近年来node.js和mongodb的确是大放异彩,在 ...

  10. node.js连接MySQL操作及注意事项

    node.js作为服务端的js运行环境已经出现了有几年了,最近我有个朋友也在做这方面的开发,但是也是刚刚接触,遇到了很多坑.前几天他们在操作数据库的时候出现了点问题,后来我们一起看了看,其实都是nod ...

随机推荐

  1. HTML杂项和HTML废弃标签

    一.HTML杂项 1.HTML注释  <!-- 里边放要注释的文字 --> 1)html的注释是为了方便后期的维护,方便后期更改时能够快速的定位到所需更改的部分 2)html的注释在页面的 ...

  2. TortoiseGit用户手册

    3 配置TortoiseGit 3.1 生成公钥 生成SSH安全密钥,提供给GIT版本库管理员以访问Git 版本库,点击桌面上生成的图标 然后执行执行“ssh-keygen”生成自己的公钥: 一路回车 ...

  3. JS基础(二)

    21.标准事件模型的事件类型(包括4个子模块) HTMLEvents:接口为Event,支持的事件类型包括abort.blur.change.error.focus.load.resize.scrol ...

  4. egg.js-基于koa2的node.js进阶(一)

    一.路由进阶Egg路由的路由重定向,路由分组 在router.js修改为如下格式require引用 module.exports = app => { const { router, contr ...

  5. 微信小程序为什么不被看好?

    我自认为对新技术还是比较有热情的,可对于小程序这个“新技术”,我却完全是被动的.去年9月份的时候,微信小程序开始内测,瞬间引爆朋友圈.知乎等一众分享平台.当时我大概了解了一下,觉得从技术角度上来说没啥 ...

  6. cookie implements session

    cookie实现会话 服务器调用response.addCookie()设置set-cookie响应头后,浏览器收到这个响应头与数值后,会将它以文件的形式存储于本地PC上.当浏览器再次访问同一Web服 ...

  7. mysql 免安装版

    通过MySQL安装程序(.msi文件)来安装虽然简洁高效,但不够灵活,所以我们这里介绍免安装版. 1.  下载: 进入官网-->Downloads-->Community(社区版)--&g ...

  8. Pig的使用场景

    数据转换加载(ETL)数据流:读取原始数据(比如用户日志),进行数据清洗,进行简单的预计算后导入到数据仓库,比如join连接数据库里的用户信息.

  9. 产生渐变色的view

    产生渐变色的view 效果 源码 https://github.com/YouXianMing/UI-Component-Collection // // GradientColorView.h // ...

  10. 多线程应用-类(thread)

    在对class thread加锁时,锁无法正常应用,函数方式没问题. 在使用class thread方法时,并发后的查询结果不对,函数方式没问题. # -*- coding: UTF-8 -*- fr ...