node-mongodb-native: Mongo DB Native NodeJS Driver:Mongo DB本机NodeJS驱动程序

API DocumentationAPI 文档 API 索引

Install安装

To install the most recent release from npm, run:要安装npm的最新版本,请运行:

npm install mongodb

That may give you a warning telling you that bugs['web'] should be bugs['url'], it would be safe to ignore it (this has been fixed in the development version)这可能会给你一个警告,告诉你bug['web']应该是bug['url'],忽略它是安全的(这在开发版本中已经修复)

To install the latest from the repository, run::要从存储库安装最新版本,请运行:

npm install path/to/node-mongodb-native

Community社区

Check out the google group node-mongodb-native for questions/answers from users of the driver.查看google群组node-mongodb-native,获取驱动程序用户的问题/答案。

Introduction介绍

This is a node.js driver for MongoDB.这是MongoDB的node.js驱动程序。It's a port (or close to a port) of the library for ruby at http://github.com/mongodb/mongo-ruby-driver/.它是位于http://github.com/mongodb/mongo-ruby-driver/的ruby库的一个端口(或接近端口)。

A simple example of inserting a document.插入文档的简单示例。

var client = new Db('test', new Server("127.0.0.1", 27017, {})),
    test = function (err, collection) {
      collection.insert({a:2}, function(err, docs) {

        collection.count(function(err, count) {
          test.assertEquals(1, count);
        });

        // Locate all the entries using find
        collection.find().toArray(function(err, results) {
          test.assertEquals(1, results.length);
          test.assertTrue(results[0].a === 2);

          // Let's close the db
          client.close();
        });
      });
    };

client.open(function(err, p_client) {
  client.collection('test_insert', test);
});

Data types数据类型

To store and retrieve the non-JSON MongoDb primitives (ObjectID, Long, Binary, Timestamp, DBRef, Code).存储和检索非JSON MongoDb原语(ObjectID、Long、Binary、TimestampDBRef、Code)。

In particular, every document has a unique _id which can be almost any type, and by default a 12-byte ObjectID is created.特别是,每个文档都有一个唯一的_id,几乎可以是任何类型,默认情况下会创建一个12字节的ObjectID。ObjectIDs can be represented as 24-digit hexadecimal strings, but you must convert the string back into an ObjectID before you can use it in the database.ObjectID可以表示为24位十六进制字符串,但必须先将字符串转换回ObjectID,然后才能在数据库中使用它。For example:例如:

// Get the objectID type
var ObjectID = require('mongodb').ObjectID;

var idString = '4e4e1638c85e808431000003';
collection.findOne({_id: new ObjectID(idString)}, console.log)  // ok
collection.findOne({_id: idString}, console.log)  // wrong! callback gets undefined

Here are the constructors the non-Javascript BSON primitive types:以下是非Javascript BSON基元类型的构造函数:

// Fetch the library
var mongo = require('mongodb');
// Create new instances of BSON types
new mongo.Long(numberString)
new mongo.ObjectID(hexString)
new mongo.Timestamp()  // the actual unique number is generated on insert.
new mongo.DBRef(collectionName, id, dbName)
new mongo.Binary(buffer)  // takes a string or Buffer
new mongo.Code(code, [context])
new mongo.Symbol(string)
new mongo.MinKey()
new mongo.MaxKey()
new mongo.Double(number)	// Force double storage

The C/C++ bson parser/serializer

From V0.8.0 to V0.9.6.9, the Javascript bson parser was slower than an optional C/C++ bson parser.从V0.8.0到V0.9.6.9,Javascript bson解析器比可选的C/C++bson解析器慢。As of V0.9.6.9+, due to performance improvements in the Javascript parser, the C/C++ parser is deprecated and is not installed by default anymore.从V0.9.6.9+开始,由于Javascript解析器的性能改进,C/C++解析器已被弃用,默认情况下不再安装。

If you are running a version of this library has the C/C++ parser compiled, to enable the driver to use the C/C++ bson parser pass it the option native_parser:true like below如果正在运行此库的某个版本并编译了C/C++解析器,则要使驱动程序能够使用C/C++bson解析器,请将选项native_parser:true传递给它,如下所示

// using Deprecated native_parser:
var client = new Db('integration_tests_20',
                    new Server("127.0.0.1", 27017),
                    {native_parser:true});

The C++ parser uses the js objects both for serialization and deserialization.C++解析器使用JS对象,既用于序列化又用于反序列化。

GitHub informationGitHub信息

The source code is available at http://github.com/christkv/node-mongodb-native.源代码可在http://github.com/christkv/node-mongodb-native找到。You can either clone the repository or download a tarball of the latest release.您可以克隆存储库或下载最新版本的tarball。

Once you have the source you can test the driver by running获得源代码后,可以在主目录中运行以下代码:

$ make test

in the main directory.You will need to have a mongo instance running on localhost for the integration tests to pass.您需要在localhost上运行一个mongo实例,集成测试才能通过。

Examples例子

For examples look in the examples/ directory. You can execute the examples using node.有关示例,请查看examples/目录。您可以使用node执行示例。

$ cd examples
$ node queries.js

GridStore

The GridStore class allows for storage of binary files in mongoDB using the mongoDB defined files and chunks collection definition.GridStore类允许使用mongoDB定义的文件和块集合定义在mongoDB中存储二进制文件。

For more information have a look at Gridstore有关更多信息,请查看Gridstore

Replicasets

For more information about how to connect to a replicaset have a look at Replicasets有关如何连接到replicaset的更多信息,请查看Replicasets

Primary Key Factories主键工厂

Defining your own primary key factory allows you to generate your own series of id's (this could f.ex be to use something like ISBN numbers).定义自己的主键工厂允许您生成自己的id系列(这可能是f.ex使用类似ISBN的数字)。The generated the id needs to be a 12 byte long "string".生成的id必须是12字节长的“字符串”。

Simple example below下面是一个简单的例子

// Custom factory (need to provide a 12 byte array);
CustomPKFactory = function() {}
CustomPKFactory.prototype = new Object();
CustomPKFactory.createPk = function() {
  return new ObjectID("aaaaaaaaaaaa");
}

var p_client = new Db('integration_tests_20', new Server("127.0.0.1", 27017, {}), {'pk':CustomPKFactory});
p_client.open(function(err, p_client) {
  p_client.dropDatabase(function(err, done) {
    p_client.createCollection('test_custom_key', function(err, collection) {
      collection.insert({'a':1}, function(err, docs) {
        collection.find({'_id':new ObjectID("aaaaaaaaaaaa")}, function(err, cursor) {
          cursor.toArray(function(err, items) {
            test.assertEquals(1, items.length);

            // Let's close the db
            p_client.close();
          });
        });
      });
    });
  });
});

Strict mode严格模式

Each database has an optional strict mode.每个数据库都有一个可选的严格模式。If it is set then asking for a collection that does not exist will return an Error object in the callback.如果设置了,则请求不存在的集合将在回调中返回错误对象。Similarly if you attempt to create a collection that already exists.类似地,如果尝试创建已存在的集合。Strict is provided for convenience.为方便起见,提供了严格的标准。

var error_client = new Db('integration_tests_', new Server("127.0.0.1", 27017, {auto_reconnect: false}), {strict:true});    
  test.assertEquals(true, error_client.strict);
  
  error_client.open(function(err, error_client) {
  error_client.collection('does-not-exist', function(err, collection) {
    test.assertTrue(err instanceof Error);
    test.assertEquals("Collection does-not-exist does not exist. Currently in strict mode.", err.message);
  });

  error_client.createCollection('test_strict_access_collection', function(err, collection) {
    error_client.collection('test_strict_access_collection', function(err, collection) {
      test.assertTrue(collection instanceof Collection);
      // Let's close the db
      error_client.close();
    });
  });
});

Documentation文档

If this document doesn't answer your questions, see the source of Collection or Cursor, or the documentation at MongoDB for query and update formats.如果此文档没有回答您的问题,请参阅CollectionCursor的来源,或MongoDB上的文档以了解查询和更新格式。

Find发现

The find method is actually a factory method to create Cursor objects.find方法实际上是创建游标对象的工厂方法。A Cursor lazily uses the connection the first time you call nextObject, each, or toArray.第一次调用nextObjecteachtoArray时,游标会惰性地使用连接。

The basic operation on a cursor is the nextObject method that fetches the next matching document from the database.对游标的基本操作是nextObject方法,它从数据库中获取下一个匹配的文档。The convenience methods each and toArray call nextObject until the cursor is exhausted.便利方法eachtoArray调用nextObject,直到游标用完为止。

Signatures:签名:

var cursor = collection.find(query, [fields], options);
cursor.sort(fields).limit(n).skip(m).

cursor.nextObject(function(err, doc) {});
cursor.each(function(err, doc) {});
cursor.toArray(function(err, docs) {});

cursor.rewind()  // reset the cursor to its initial state.

Useful chainable methods of cursor.有用的游标链接方法。These can optionally be options of find instead of method calls:这些选项可以是find选项,而不是方法调用选项:

Other options of find:find的其他选项:

For information on how to create queries, see the MongoDB section on querying.有关如何创建查询的信息,请参阅MongoDB查询部分

var mongodb = require('mongodb');
var server = new mongodb.Server("127.0.0.1", 27017, {});
new mongodb.Db('test', server, {}).open(function (error, client) {
  if (error) throw error;
  var collection = new mongodb.Collection(client, 'test_collection');
  collection.find({}, {limit:10}).toArray(function(err, docs) {
    console.dir(docs);
  });
});

Insert

Signature:签名:

collection.insert(docs, options, [callback]);

where docs can be a single document or an array of documents.其中,docs可以是单个文档或文档数组。

Useful options:有用的选项:

See also: MongoDB docs for insert.另请参见:MongoDB文档以了解插入

var mongodb = require('mongodb');
var server = new mongodb.Server("127.0.0.1", 27017, {});
new mongodb.Db('test', server, {}).open(function (error, client) {
  if (error) throw error;
  var collection = new mongodb.Collection(client, 'test_collection');
  collection.insert({hello: 'world'}, {safe:true},
                    function(err, objects) {
    if (err) console.warn(err.message);
    if (err && err.message.indexOf('E11000 ') !== -1) {
      // this _id was already inserted in the database
    }
  });
});

Note that there's no reason to pass a callback to the insert or update commands unless you use the safe:true option.请注意,除非使用safe:true选项,否则没有理由向insert或update命令传递回调。If you don't specify safe:true, then your callback will be called immediately.如果未指定safe:true,则将立即调用回调。

Update; update and insert (upsert)使现代化更新和插入(向上插入)

The update operation will update the first document that matches your query (or all documents that match if you use multi:true).更新操作将更新与查询匹配的第一个文档(如果使用multi:true,则更新匹配的所有文档)。If safe:true, upsert is not set, and no documents match, your callback will be given an error.如果safe:true,未设置upsert,并且没有文档匹配,则回调将出现错误。

See the MongoDB docs for the modifier ($inc, $set, $push, etc.) formats.有关修改器($inc$set$push等)格式,请参阅MongoDB文档

Signature:签名:

collection.update(criteria, objNew, options, [callback]);

Useful options:有用的选项:

Example for update:update示例:

var mongodb = require('mongodb');
var server = new mongodb.Server("127.0.0.1", 27017, {});
new mongodb.Db('test', server, {}).open(function (error, client) {
  if (error) throw error;
  var collection = new mongodb.Collection(client, 'test_collection');
  collection.update({hi: 'here'}, {$set: {hi: 'there'}}, {safe:true},
                    function(err) {
    if (err) console.warn(err.message);
    else console.log('successfully updated');
  });
});

Find and modify查找和修改

findAndModify is like update, but it also gives the updated document to your callback.findAndModifyupdate类似,但它也会将更新后的文档提供给回调。But there are a few key differences between findAndModify and update:但findAndModify和update之间有几个关键区别:

  1. The signatures differ.签名不同。
  2. You can only findAndModify a single item, not multiple items.您只能查找和修改单个项目,不能修改多个项目。

Signature:签名:

collection.findAndModify(query, sort, update, options, callback)

The sort parameter is used to specify which object to operate on, if more than one document matches.如果有多个文档匹配,则sort参数用于指定要对哪个对象进行操作。It takes the same format as the cursor sort (see Connection.find above).它采用与游标排序相同的格式(请参见上面的Connection.find)。

See the MongoDB docs for findAndModify for more details.有关更多详细信息,请参阅MongoDB文档中的FindModify

Useful options:有用的选项:

Example for findAndModify:findAndModify示例:

var mongodb = require('mongodb');
var server = new mongodb.Server("127.0.0.1", 27017, {});
new mongodb.Db('test', server, {}).open(function (error, client) {
  if (error) throw error;
  var collection = new mongodb.Collection(client, 'test_collection');
  collection.findAndModify({hello: 'world'}, [['_id','asc']], {$set: {hi: 'there'}}, {},
                    function(err, object) {
    if (err) console.warn(err.message);
    else console.dir(object);  // undefined if no matching object exists.
  });
});

Save保存

The save method is a shorthand for upsert if the document contains an _id, or an insert if there is no _id.如果文档包含_idsave方法是upsert的简写,如果没有_idsave方法是insert

Sponsors赞助商

Just as Felix Geisendörfer I'm also working on the driver for my own startup and this driver is a big project that also benefits other companies who are using MongoDB.正如Felix Geisendrfer一样,我也在为自己的创业公司开发驱动程序,这个驱动程序是一个大项目,也有利于其他使用MongoDB的公司。

If your company could benefit from a even better-engineered node.js mongodb driver I would appreciate any type of sponsorship you may be able to provide.如果您的公司能够从一个更好的node.js mongodb驱动程序中获益,我将非常感谢您提供的任何类型的赞助。All the sponsors will get a lifetime display in this readme, priority support and help on problems and votes on the roadmap decisions for the driver.所有赞助商将在本自述中获得终身展示,优先支持和问题帮助,并对驾驶员的路线图决策进行投票。If you are interested contact me on christkv AT g m a i l.com for details.如果您感兴趣,请通过christkv@gmail.com联系我。

And I'm very thankful for code contributions.我非常感谢代码贡献。If you are interested in working on features please contact me so we can discuss API design and testing.如果您对功能感兴趣,请与我联系,以便我们可以讨论API设计和测试。

Release Notes发行说明

See HISTORY请参阅历史

Credits信用

  1. 10gen
  2. Google Closure Library
  3. Jonas Raoni Soares Silva

Contributors贡献者

Aaron Heckmann, Christoph Pojer, Pau Ramon Revilla, Nathan White, Emmerman, Seth LaForge, Boris Filipov, Stefan Schärmeli, Tedde Lundgren, renctan, Sergey Ukustov, Ciaran Jessup, kuno, srimonti, Erik Abele, Pratik Daga, Slobodan Utvic, Kristina Chodorow, Yonathan Randolph, Brian Noguchi, Sam Epstein, James Harrison Fisher, Vladimir Dronnikov, Ben Hockey, Henrik Johansson, Simon Weare, Alex Gorbatchev, Shimon Doodkin, Kyle Mueller, Eran Hammer-Lahav, Marcin Ciszak, François de Metz, Vinay Pulim, nstielau, Adam Wiggins, entrinzikyl, Jeremy Selier, Ian Millington, Public Keating, andrewjstone, Christopher Stott, Corey Jewett, brettkiefer, Rob Holland, Senmiao Liu, heroic, gitfy

License许可证

Copyright 2009 - 2010 Christian Amor Kvalheim.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.根据Apache许可证2.0版(以下简称“许可证”)获得许可;除非遵守许可证,否则不得使用此文件。You may obtain a copy of the License at您可以通过以下方式获得许可证副本:

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.