10 Check out the google group http://groups.google.com/group/node-mongodb-native for questions/answers from users of the driver.
15 This is a node.js driver for MongoDB. It's a port (or close to a port) of the libary for ruby at http://github.com/mongodb/mongo-ruby-driver/.
17 A simple example of inserting a document.
19 var client = new Db('test', new Server("127.0.0.1", 27017, {})),
20 test = function (err, collection) {
21 collection.insert({a:2}, function(err, docs) {
23 collection.count(function(err, count) {
24 test.assertEquals(1, count);
27 // Locate all the entries using find
28 collection.find().toArray(function(err, results) {
29 test.assertEquals(1, results.length);
30 test.assertTrue(results.a === 2);
38 client.open(function(err, p_client) {
39 client.collection('test_insert', test);
45 To enable the driver to use the C/C++ bson parser pass it the option native_parser:true like below
47 var client = new Db('integration_tests_20',
48 new Server("127.0.0.1", 27017),
49 {native_parser:true});
51 The version V0.8.0 > contains a C/C++ native BSON parser, this leads to some small changes in the way you need to access the BSON classes as you need to use the right versions of the classes with the right driver.
53 To access the correct version of BSON objects for your instance do the following
55 client.bson_serializer.Long
56 client.bson_serializer.ObjectID
57 client.bson_serializer.Timestamp
58 client.bson_serializer.DBRef
59 client.bson_serializer.Binary
60 client.bson_serializer.Code
65 The source code is available at http://github.com/christkv/node-mongodb-native.
66 You can either clone the repository or download a tarball of the latest release.
68 Once you have the source you can test the driver by running
72 in the main directory. You will need to have a mongo instance running on localhost for the integration tests to pass.
77 For examples look in the examples/ directory. You can execute the examples using node.
85 The GridStore class allows for storage of binary files in mongoDB using the mongoDB defined files and chunks collection definition.
87 For more information have a look at [Gridstore](https://github.com/christkv/node-mongodb-native/blob/master/docs/gridfs.md)
91 For more information about how to connect to a replicaset have a look at [Replicasets](https://github.com/christkv/node-mongodb-native/blob/master/docs/replicaset.md)
96 The current version does not support connection pooling, but it will be implemented
102 Defining your own primary key factory allows you to generate your own series of id's
103 (this could f.ex be to use something like ISBN numbers). The generated the id needs to be a 12 byte long "string".
107 // Custom factory (need to provide a 12 byte array);
108 CustomPKFactory = function() {}
109 CustomPKFactory.prototype = new Object();
110 CustomPKFactory.createPk = function() {
111 return new ObjectID("aaaaaaaaaaaa");
114 var p_client = new Db('integration_tests_20', new Server("127.0.0.1", 27017, {}), {'pk':CustomPKFactory});
115 p_client.open(function(err, p_client) {
116 p_client.dropDatabase(function(err, done) {
117 p_client.createCollection('test_custom_key', function(err, collection) {
118 collection.insert({'a':1}, function(err, docs) {
119 collection.find({'_id':new ObjectID("aaaaaaaaaaaa")}, function(err, cursor) {
120 cursor.toArray(function(err, items) {
121 test.assertEquals(1, items.length);
123 // Let's close the db
135 Each database has an optional strict mode. If it is set then asking for a collection
136 that does not exist will return an Error object in the callback. Similarly if you
137 attempt to create a collection that already exists. Strict is provided for convenience.
139 var error_client = new Db('integration_tests_', new Server("127.0.0.1", 27017, {auto_reconnect: false}), {strict:true});
140 test.assertEquals(true, error_client.strict);
142 error_client.open(function(err, error_client) {
143 error_client.collection('does-not-exist', function(err, collection) {
144 test.assertTrue(err instanceof Error);
145 test.assertEquals("Collection does-not-exist does not exist. Currently in strict mode.", err.message);
148 error_client.createCollection('test_strict_access_collection', function(err, collection) {
149 error_client.collection('test_strict_access_collection', function(err, collection) {
150 test.assertTrue(collection instanceof Collection);
151 // Let's close the db
152 error_client.close();
160 If this document doesn't answer your questions, see the source of
161 [Collection](https://github.com/christkv/node-mongodb-native/blob/master/lib/mongodb/collection.js)
162 or [Cursor](https://github.com/christkv/node-mongodb-native/blob/master/lib/mongodb/cursor.js),
163 or the documentation at MongoDB for query and update formats.
168 The find method is actually a factory method to create
169 Cursor objects. A Cursor lazily uses the connection the first time
170 you call `nextObject`, `each`, or `toArray`.
172 The basic operation on a cursor is the `nextObject` method
173 that fetches the next object from the database. The convenience methods
174 `each` and `toArray` call `nextObject` until the cursor is exhausted.
178 collection.find(query, [fields], options);
180 cursor.nextObject(function(err, doc) {});
181 cursor.each(function(err, doc) {});
182 cursor.toArray(function(err, docs) {});
184 cursor.rewind() // reset the cursor to its initial state.
186 Useful options of `find`:
188 * **`limit`** and **`skip`** numbers used to control paging.
189 * **`sort`** an array of sort preferences like this:
190 `[['field1','asc'], ['field2','desc']]`. As a shorthand, ascending fields can
191 be written as simply the field name instead of `['field','asc']`. Furthermore,
192 if you are sorting by a single ascending field, you can smply enter the field
193 name as a string without the surrounding array.
194 * **`fields`** the fields to fetch (to avoid transferring the entire document)
195 * **`tailable`** if true, makes the cursor [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors).
196 * **`batchSize`** The number of the subset of results to request the database
197 to return for every request. This should initially be greater than 1 otherwise
198 the database will automatically close the cursor. The batch size can be set to 1
199 with `batchSize(n, function(err){})` after performing the initial query to the database.
200 * **`hint`** See [Optimization: hint](http://www.mongodb.org/display/DOCS/Optimization#Optimization-Hint).
201 * **`explain`** turns this into an explain query. You can also call
202 `explain()` on any cursor to fetch the explanation.
203 * **`snapshot`** prevents documents that are updated while the query is active
204 from being returned multiple times. See more
205 [details about query snapshots](http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database).
206 * **`timeout`** if false, asks MongoDb not to time out this cursor after an
210 For information on how to create queries, see the
211 [MongoDB section on querying](http://www.mongodb.org/display/DOCS/Querying).
213 var mongodb = require('mongodb');
214 var server = new mongodb.Server("127.0.0.1", 27017, {});
215 new mongodb.Db('test', server, {}).open(function (error, client) {
216 if (error) throw error;
217 var collection = new mongodb.Collection(client, 'test_collection');
218 collection.find({}, {limit:10}).toArray(function(err, docs) {
228 collection.insert(docs, options, [callback]);
232 * **`safe:true`** Should always set if you have a callback.
234 See also: [MongoDB docs for insert](http://www.mongodb.org/display/DOCS/Inserting).
236 var mongodb = require('mongodb');
237 var server = new mongodb.Server("127.0.0.1", 27017, {});
238 new mongodb.Db('test', server, {}).open(function (error, client) {
239 if (error) throw error;
240 var collection = new mongodb.Collection(client, 'test_collection');
241 collection.insert({hello: 'world'}, {safe:true},
242 function(err, objects) {
243 if (err) console.warn(err.message);
244 if (err && err.message.indexOf('E11000 ') !== -1) {
245 // this _id was already inserted in the database
250 Note that there's no reason to pass a callback to the insert or update commands
251 unless you use the `safe:true` option. If you don't specify `safe:true`, then
252 your callback will be called immediately. (fine for collecting some statistics,
253 bad for most use cases (see "MongoDB is Web Scale")).
255 Update; update and insert (upsert)
258 The update operation will update the first document that matches your query
259 (or all documents that match if you use `multi:true`).
260 If `safe:true`, `upsert` is not set, and no documents match, your callback
261 will be given an error.
263 See the [MongoDB docs](http://www.mongodb.org/display/DOCS/Updating) for
264 the modifier (`$inc`, etc.) formats.
268 collection.update(criteria, objNew, options, [callback]);
272 * **`safe:true`** Should always set if you have a callback.
273 * **`multi:true`** If set, all matching documents are updated, not just the first.
274 * **`upsert:true`** Atomically inserts the document if no documents matched.
276 Example for `update`:
278 var mongodb = require('mongodb');
279 var server = new mongodb.Server("127.0.0.1", 27017, {});
280 new mongodb.Db('test', server, {}).open(function (error, client) {
281 if (error) throw error;
282 var collection = new mongodb.Collection(client, 'test_collection');
283 collection.update({hi: 'here'}, {$set: {hi: 'there'}}, {safe:true},
285 if (err) console.warn(err.message);
286 else console.log('successfully updated');
293 `findAndModify` is like `update`, but it also gives the updated document to
294 your callback. But there are a few key differences between findAndModify and
297 1. The signatures differ.
298 2. You can only findAndModify a single item, not multiple items.
299 3. The callback does not get an error when the item doesn't exist, just
300 an `undefined` object.
304 collection.findAndModify(query, sort, update, options, callback)
306 The sort parameter is used to specify which object to operate on, if more than
307 one document matches. It takes the same format as the cursor sort (see
308 Connection.find above).
311 [MongoDB docs for findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command)
316 * **`remove:true`** set to a true to remove the object before returning
317 * **`new:true`** set to true if you want to return the modified object rather than the original. Ignored for remove.
318 * **`upsert:true`** Atomically inserts the document if no documents matched.
320 Example for `findAndModify`:
322 var mongodb = require('mongodb');
323 var server = new mongodb.Server("127.0.0.1", 27017, {});
324 new mongodb.Db('test', server, {}).open(function (error, client) {
325 if (error) throw error;
326 var collection = new mongodb.Collection(client, 'test_collection');
327 collection.findAndModify({hello: 'world'}, [['_id','asc']], {$set: {hi: 'there'}}, {},
328 function(err, object) {
329 if (err) console.warn(err.message);
330 else console.dir(object); // undefined if no matching object exists.
342 The `save` method is a shorthand for upsert if the document contains an
343 `_id`, or an insert if there is no `_id`.
347 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.
349 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. 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@gmail.com](mailto:christkv@gmail.com) for details.
351 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.
361 1. [10gen](http://github.com/mongodb/mongo-ruby-driver/)
362 2. [Google Closure Library](http://code.google.com/closure/library/)
363 3. [Jonas Raoni Soares Silva](http://jsfromhell.com/classes/binary-parser)
368 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
373 Copyright 2009 - 2010 Christian Amor Kvalheim.
375 Licensed under the Apache License, Version 2.0 (the "License");
376 you may not use this file except in compliance with the License.
377 You may obtain a copy of the License at
379 http://www.apache.org/licenses/LICENSE-2.0
381 Unless required by applicable law or agreed to in writing, software
382 distributed under the License is distributed on an "AS IS" BASIS,
383 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
384 See the License for the specific language governing permissions and
385 limitations under the License.