MongoDB

Module: mongodb

Installation

1
$ npm install mongodb

Example (v2.*)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var MongoClient = require('mongodb').MongoClient 
//引用插件mongodb的MongoClient方法

MongoClient.connect('mongodb://localhost:27017/animals', function (err, db) {
//使用mongodb的MongoClient方法,connect连接到mongodb里的一个animals数据库

if (err) throw err
//如果错误就提示

db.collection('mammals').find().toArray(function (err, result) {
//执行结果,查找mammals集合,并find()显示出来,以array组形式

if (err) throw err
//如果错误就提示

console.log(result)
//控制台打印
})
})

Example (v3.*)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var MongoClient = require('mongodb').MongoClient
//引用插件mongodb的MongoClient方法

MongoClient.connect('mongodb://localhost:27017/animals', function (err, client) {
//使用mongodb的MongoClient方法,connect连接到mongodb里的一个animals数据库
//client客户端
if (err) throw err
//如果错误就提示

var db = client.db('animals')
//db等于client客户端,(v3.*)新版本加的

db.collection('mammals').find().toArray(function (err, result) {
//执行结果,查找mammals集合,并find()显示出来,以array组形式

if (err) throw err
//如果错误就提示

console.log(result)
//控制台打印
})
})

If you want an object model driver for MongoDB, look at Mongoose.

描述

Node.js 的官方MongoDB驱动程序。在mongodb-core之上提供高级API ,适用于最终用户。

注意:最近发布了v3.x,其中包含重大的API更改。您可以在此处找到更改列表。

MongoDB Node.JS驱动程序

什么 哪里
文件 http://mongodb.github.io/node-mongodb-native
API-DOC http://mongodb.github.io/node-mongodb-native/3.1/api
资源 https://github.com/mongodb/node-mongodb-native
MongoDB的 http://www.mongodb.org

错误/功能请求

认为你发现了一个错误?想要看到新功能node-mongodb-native吗?请在我们的问题管理工具JIRA中打开一个案例:

JIRA中针对所有驱动程序项目(即NODE,PYTHON,CSHARP,JAVA)和核心服务器(即SERVER)项目的错误报告都是公开的

支持/反馈

有关Node.js驱动程序的问题,疑问或反馈,请查看我们的支持渠道。请不要直接向任何驱动程序开发人员发送问题或问题 - 您更有可能在Google网上论坛的mongodb用户列表中获得答案。

更改日志

可以在中找到更改历史记录HISTORY.md

兼容性

有关版本兼容性矩阵,请参阅以下链接:

安装

开始使用Node.js 3.0驱动程序的推荐方法是使用npm(节点包管理器)在项目中安装依赖项。

MongoDB驱动程序

鉴于您已使用npm init我们创建自己的项目,我们通过执行以下npm命令来安装MongoDB驱动程序及其依赖项。

1
npm install mongodb --save

这将下载MongoDB驱动程序并在您的package.json文件中添加依赖项。

您也可以使用Yarn包管理器。

故障排除

MongoDB驱动程序依赖于其他几个包。这些是:

kerberos软件包是C ++扩展,需要在您的系统上安装构建环境。您必须能够自己构建Node.js才能编译和安装kerberos模块。此外,该kerberos模块需要MIT Kerberos包才能在UNIX操作系统上正确编译。有关要安装的库,请咨询UNIX操作系统包管理器。

Windows已包含用于Kerberos身份验证的SSPI API。但是,您需要使用Visual Studio C ++安装完整的编译器工具链才能正确安装Kerberos扩展。

在UNIX上进行诊断

如果您没有build-essentials,则不会构建此模块。对于Linux,你需要gcc,g ++,Node.js以及所有头文件和Python。找出缺少的最简单的方法是尝试构建Kerberos项目。您可以通过执行以下步骤来执行此操作。

1
2
3
git clone https://github.com/mongodb-js/kerberos
cd kerberos
npm install

如果所有步骤都已完成,则表明您已安装了正确的工具链。如果您收到错误“找不到node-gyp”,则需要node-gyp全局安装:

1
npm install -g node-gyp

如果它正确编译并运行测试,那么你就是金色的。我们现在可以尝试mongod通过执行以下命令来安装驱动程序。

1
2
cd yourproject
npm install mongodb --save

如果仍然失败,则下一步是检查npm日志。重新运行命令,但在这种情况下是详细模式。

1
npm --loglevel verbose install mongodb

这将打印出在尝试安装模块时npm正在执行的所有步骤。

在Windows上进行诊断

已知可kerberos在Windows上进行编译的编译器工具链如下所示。

  • Visual Studio C ++ 2010(不要使用更高版本)
  • Windows 7 64位SDK
  • Python 2.7或更高版本

打开Visual Studio命令提示符。确保node.exe在您的路径中并安装node-gyp

1
npm install -g node-gyp

接下来,您必须手动构建项目以进行测试。克隆存储库,安装依赖项并重建:

1
2
3
4
git clone https://github.com/christkv/kerberos.git
cd kerberos
npm install
node-gyp rebuild

如果您已正确设置所有内容,则应成功重建驱动程序。

其他可能的问题

您的Python安装可能需要进行gyp break。首先通过尝试在有问题的服务器上构建Node.js来测试您的部署环境,因为这应该能够解决破坏软件包的任何问题(并且有很多破解的软件包)。

另一个提示是确保您的用户具有对安装Node.js模块的任何位置的写入权限。

快速开始

本指南将向您展示如何使用Node.js和MongoDB设置一个简单的应用程序。它的范围只是如何设置驱动程序和执行简单的CRUD操作。有关更深入的报道,请参阅教程

创建package.json文件

首先,创建一个应用程序所在的目录。

1
2
mkdir myproject
cd myproject

输入以下命令并回答问题以创建新项目的初始结构:

1
npm init

接下来,安装驱动程序依赖项。

1
npm install mongodb --save

你应该看到NPM下载了很多文件。完成后,您将在node_modules目录下找到所有下载的软件包。

启动MongoDB服务器

有关完整的MongoDB安装说明,请参阅手册

  1. MongoDB下载正确的MongoDB版本
  2. 创建一个数据库目录(在本例中为/ data)。
  3. 安装并启动一个mongod过程。
1
mongod --dbpath = / data

您应该看到mongod进程启动并打印一些状态信息。

连接到MongoDB

创建一个新的app.js文件并添加以下代码以使用MongoDB驱动程序尝试一些基本的CRUD操作。

添加代码以连接到服务器和数据库myproject

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const  MongoClient  =  require' mongodb ')。MongoClient ;
const assert = require' assert ');

//连接URL
const url = ' mongodb:// localhost:27017 ' ;

//数据库名称
const dbName = ' myproject ' ;

//使用connect方法连接到服务器
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");

const db = client.db(dbName);

client.close();
});

从命令行运行您的应用程序:

1
node app.js

应用程序应成功将已连接打印到服务器到控制台。

插入文档

app.js添加以下函数,该函数使用insertMany 方法将三个文档添加到文档集合中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const  insertDocuments  =  functiondbcallback{
//获取文档集合
const collection = db.collection('documents');
//插入一些文档
collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) {
assert.equal(err, null);
assert.equal(3, result.result.n);
assert.equal(3, result.ops.length);
console.log("Inserted 3 documents into the collection");
callback(result);
});
}

所述插入件命令返回具有以下字段的对象:

  • result包含MongoDB的结果文档
  • ops包含使用添加的_id字段插入的文档
  • connection包含用于执行插入的连接

添加以下代码以调用insertDocuments函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const  MongoClient  =  require' mongodb ')。MongoClient ;
const assert = require' assert ');

//连接URL
const url = ' mongodb:// localhost:27017 ' ;

//数据库名称
const dbName = ' myproject ' ;

//使用connect方法连接到服务器
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");

const db = client.db(dbName);

insertDocuments(db, function() {
client.close();
});
});

运行更新的app.js文件:

1
node app.js

该操作返回以下输出:

1
2
已成功连接到服务器
在集合中插入3个文档

查找所有文档

添加一个返回所有文档的查询。

1
2
3
4
5
6
7
8
9
10
11
const  findDocuments  =  functiondbcallback{
//获取文档集合
const collection = db.collection('documents');
//找一些文件
collection.find({}).toArray(function(err, docs) {
assert.equal(err,npx ll);
console.log("Found the following records");
console.log(docs)
callback(docs);
});
}

此查询返回文档集合中的所有文档。将findDocument方法添加到MongoClient.connect回调:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const  MongoClient  =  require' mongodb ')。MongoClient ;
const assert = require' assert ');

//连接URL
const url = ' mongodb:// localhost:27017 ' ;

//数据库名称
const dbName = ' myproject ' ;

//使用connect方法连接到服务器
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected correctly to server");

const db = client.db(dbName);

insertDocuments(db, function() {
findDocuments(db, function() {
client.close();
});
});
});

使用查询过滤器查找文档

添加查询过滤器以仅查找符合查询条件的文档。

1
2
3
4
5
6
7
8
9
10
11
const  findDocuments  =  functiondbcallback{
//获取文档集合
const collection = db.collection('documents');
//找一些文件
collection.find({'a': 3}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
console.log(docs);
callback(docs);
});
}

'a' : 3应返回匹配的文档。

更新文档

以下操作更新文档集合中的文档

1
2
3
4
5
6
7
8
9
10
11
12
const  updateDocument  =  functiondbcallback{
//获取文档集合
const collection = db.collection('documents');
//更新文件,其中a为2,设置b等于1个
collection.updateOne({ a : 2 }
, { $set: { b : 1 } }, function(err, result) {
assert.equal(err, null);
assert.equal(1, result.result.n);
console.log("Updated the document with the field a equal to 2");
callback(result);
});
}

该方法通过将新字段b添加到文档集1来更新字段a等于2的第一个文档。接下来,从MongoClient.connect更新回调函数以包含更新方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const  MongoClient  =  require' mongodb ')。MongoClient ;
const assert = require' assert ');

//连接URL
const url = ' mongodb:// localhost:27017 ' ;

//数据库名称
const dbName = ' myproject ' ;

//使用connect方法连接到服务器
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");

const db = client.db(dbName);

insertDocuments(db, function() {
updateDocument(db, function() {
client.close();
});
});
});

删除文档

删除字段a等于3的文档。

1
2
3
4
5
6
7
8
9
10
11
const  removeDocument  =  functiondbcallback{
//获取文档集合
const collection = db.collection('documents');
//删除a为3
collection.deleteOne({ a : 3 }, function(err, result) {
assert.equal(err, null);
assert.equal(1, result.result.n);
console.log("Removed the document with the field a equal to 3");
callback(result);
});
}

将新方法添加到MongoClient.connect回调函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const  MongoClient  =  require' mongodb ')。MongoClient ;
const assert = require' assert ');

//连接URL
const url = ' mongodb:// localhost:27017 ' ;

//数据库名称
const dbName = ' myproject ' ;

//使用connect方法连接到服务器
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");

const db = client.db(dbName);

insertDocuments(db, function() {
updateDocument(db, function() {
removeDocument(db, function() {
client.close();
});
});
});
});

索引集合

索引可以提高应用程序的性能。以下函数在文档集合中字段 上创建索引。

1
2
3
4
5
6
7
8
9
10
const indexCollection = function(db, callback) {
db.collection('documents').createIndex(
{ "a": 1 },
null,
function(err, results) {
console.log(results);
callback();
}
);
};

indexCollection方法添加到您的应用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const  MongoClient  =  require' mongodb ')。MongoClient ;
const assert = require' assert ');

//连接URL
const url = ' mongodb:// localhost:27017 ' ;

const dbName = ' myproject ' ;

//使用connect方法连接到服务器
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log(“成功连接到服务器”);

const db = client.db(dbName);

insertDocuments(db, function() {
indexCollection(db, function() {
client.close();
});
});
});

有关更多详细信息,请参阅教程



本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!