Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 414 lines (300 sloc) 16.515 kb
66ca386 @christkv Updated doc, readme, package
authored
1 Main Documentation site
2 =======================
3
57a3827 @christkv Updated docs
authored
4 [Documentation](http://christkv.github.com/node-mongodb-native/)
66ca386 @christkv Updated doc, readme, package
authored
5
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
6 Install
7 ========
8
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
9 To install the most recent release from npm, run:
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
10
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
11 npm install mongodb
d4f3a6e @Poincare Updated README.md
Poincare authored
12
13 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)
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
14
eba3fd4 @bencevans Update Readme.md
bencevans authored
15 To install the latest from the repository, run::
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
16
17 npm install path/to/node-mongodb-native
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
18
19 Community
20 ========
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
21 Check out the google group [node-mongodb-native](http://groups.google.com/group/node-mongodb-native) for questions/answers from users of the driver.
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
22
23 Introduction
24 ========
25
c333f6f @sahilm
sahilm authored
26 This is a node.js driver for MongoDB. It's a port (or close to a port) of the library for ruby at http://github.com/mongodb/mongo-ruby-driver/.
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
27
28 A simple example of inserting a document.
29
e4a0fe4 @masylum docs changes
masylum authored
30 var client = new Db('test', new Server("127.0.0.1", 27017, {})),
31 test = function (err, collection) {
32 collection.insert({a:2}, function(err, docs) {
33
34 collection.count(function(err, count) {
35 test.assertEquals(1, count);
36 });
37
38 // Locate all the entries using find
39 collection.find().toArray(function(err, results) {
40 test.assertEquals(1, results.length);
157528e @christkv Fix for readme
authored
41 test.assertTrue(results[0].a === 2);
e4a0fe4 @masylum docs changes
masylum authored
42
43 // Let's close the db
44 client.close();
45 });
46 });
47 };
48
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
49 client.open(function(err, p_client) {
e4a0fe4 @masylum docs changes
masylum authored
50 client.collection('test_insert', test);
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
51 });
52
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
53 Data types
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
54 ========
e4a0fe4 @masylum docs changes
masylum authored
55
317e66a @christkv Finished up bug fixes in bson, fixed documentation
authored
56 To store and retrieve the non-JSON MongoDb primitives ([ObjectID](http://www.mongodb.org/display/DOCS/Object+IDs), Long, Binary, [Timestamp](http://www.mongodb.org/display/DOCS/Timestamp+data+type), [DBRef](http://www.mongodb.org/display/DOCS/Database+References#DatabaseReferences-DBRef), Code).
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
57
fb1bdbc @christkv Documentation fix
authored
58 In particular, every document has a unique `_id` which can be almost any type, and by default a 12-byte ObjectID is created. 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. For example:
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
59
a1307fb @christkv Documentation fix
authored
60 // Get the objectID type
61 var ObjectID = require('mongodb').ObjectID;
62
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
63 var idString = '4e4e1638c85e808431000003';
317e66a @christkv Finished up bug fixes in bson, fixed documentation
authored
64 collection.findOne({_id: new ObjectID(idString)}, console.log) // ok
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
65 collection.findOne({_id: idString}, console.log) // wrong! callback gets undefined
66
67 Here are the constructors the non-Javascript BSON primitive types:
68
a1307fb @christkv Documentation fix
authored
69 // Fetch the library
70 var mongo = require('mongodb');
007a1ce @christkv Documentation fix
authored
71 // Create new instances of BSON types
317e66a @christkv Finished up bug fixes in bson, fixed documentation
authored
72 new mongo.Long(numberString)
73 new mongo.ObjectID(hexString)
74 new mongo.Timestamp() // the actual unique number is generated on insert.
75 new mongo.DBRef(collectionName, id, dbName)
76 new mongo.Binary(buffer) // takes a string or Buffer
77 new mongo.Code(code, [context])
78 new mongo.Symbol(string)
79 new mongo.MinKey()
80 new mongo.MaxKey()
81 new mongo.Double(number) // Force double storage
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
82
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
83 The C/C++ bson parser/serializer
84 --------
85
4265409 @Poincare Fixed one letter typo
Poincare authored
86 From V0.8.0 to V0.9.6.9, the Javascript bson parser was slower than an optional C/C++ bson parser. 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.
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
87
88 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
89
90 // using Deprecated native_parser:
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
91 var client = new Db('integration_tests_20',
92 new Server("127.0.0.1", 27017),
93 {native_parser:true});
933c82f @christkv Changes to docs
authored
94
317e66a @christkv Finished up bug fixes in bson, fixed documentation
authored
95 The C++ parser uses the js objects both for serialization and deserialization.
e4a0fe4 @masylum docs changes
masylum authored
96
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
97 GitHub information
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
98 ========
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
99
100 The source code is available at http://github.com/christkv/node-mongodb-native.
101 You can either clone the repository or download a tarball of the latest release.
102
103 Once you have the source you can test the driver by running
104
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
105 $ make test
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
106
107 in the main directory. You will need to have a mongo instance running on localhost for the integration tests to pass.
108
109 Examples
110 ========
111
112 For examples look in the examples/ directory. You can execute the examples using node.
113
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
114 $ cd examples
115 $ node queries.js
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
116
117 GridStore
0b5d097 @christkv Added replicaset doc
authored
118 =========
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
119
120 The GridStore class allows for storage of binary files in mongoDB using the mongoDB defined files and chunks collection definition.
121
f00ec53 @christkv Update doc
authored
122 For more information have a look at [Gridstore](https://github.com/christkv/node-mongodb-native/blob/master/docs/gridfs.md)
0b5d097 @christkv Added replicaset doc
authored
123
124 Replicasets
125 ===========
f00ec53 @christkv Update doc
authored
126 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)
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
127
128 Primary Key Factories
129 --------
130
131 Defining your own primary key factory allows you to generate your own series of id's
132 (this could f.ex be to use something like ISBN numbers). The generated the id needs to be a 12 byte long "string".
133
134 Simple example below
135
4295cd5 @christkv Fixed readme
authored
136 // Custom factory (need to provide a 12 byte array);
137 CustomPKFactory = function() {}
138 CustomPKFactory.prototype = new Object();
139 CustomPKFactory.createPk = function() {
140 return new ObjectID("aaaaaaaaaaaa");
141 }
142
143 var p_client = new Db('integration_tests_20', new Server("127.0.0.1", 27017, {}), {'pk':CustomPKFactory});
144 p_client.open(function(err, p_client) {
145 p_client.dropDatabase(function(err, done) {
146 p_client.createCollection('test_custom_key', function(err, collection) {
147 collection.insert({'a':1}, function(err, docs) {
148 collection.find({'_id':new ObjectID("aaaaaaaaaaaa")}, function(err, cursor) {
149 cursor.toArray(function(err, items) {
150 test.assertEquals(1, items.length);
151
152 // Let's close the db
153 p_client.close();
154 });
e4a0fe4 @masylum docs changes
masylum authored
155 });
156 });
157 });
158 });
159 });
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
160
161 Strict mode
162 --------
163
164 Each database has an optional strict mode. If it is set then asking for a collection
165 that does not exist will return an Error object in the callback. Similarly if you
e4a0fe4 @masylum docs changes
masylum authored
166 attempt to create a collection that already exists. Strict is provided for convenience.
167
4295cd5 @christkv Fixed readme
authored
168 var error_client = new Db('integration_tests_', new Server("127.0.0.1", 27017, {auto_reconnect: false}), {strict:true});
169 test.assertEquals(true, error_client.strict);
170
171 error_client.open(function(err, error_client) {
172 error_client.collection('does-not-exist', function(err, collection) {
173 test.assertTrue(err instanceof Error);
174 test.assertEquals("Collection does-not-exist does not exist. Currently in strict mode.", err.message);
175 });
e4a0fe4 @masylum docs changes
masylum authored
176
4295cd5 @christkv Fixed readme
authored
177 error_client.createCollection('test_strict_access_collection', function(err, collection) {
178 error_client.collection('test_strict_access_collection', function(err, collection) {
179 test.assertTrue(collection instanceof Collection);
180 // Let's close the db
181 error_client.close();
182 });
e4a0fe4 @masylum docs changes
masylum authored
183 });
184 });
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
185
186 Documentation
187 ========
188
189 If this document doesn't answer your questions, see the source of
0b5d097 @christkv Added replicaset doc
authored
190 [Collection](https://github.com/christkv/node-mongodb-native/blob/master/lib/mongodb/collection.js)
191 or [Cursor](https://github.com/christkv/node-mongodb-native/blob/master/lib/mongodb/cursor.js),
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
192 or the documentation at MongoDB for query and update formats.
193
194 Find
195 --------
196
6b23aac @yonran Typos and formatting.
yonran authored
197 The find method is actually a factory method to create
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
198 Cursor objects. A Cursor lazily uses the connection the first time
199 you call `nextObject`, `each`, or `toArray`.
200
201 The basic operation on a cursor is the `nextObject` method
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
202 that fetches the next matching document from the database. The convenience
203 methods `each` and `toArray` call `nextObject` until the cursor is exhausted.
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
204
205 Signatures:
206
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
207 var cursor = collection.find(query, [fields], options);
208 cursor.sort(fields).limit(n).skip(m).
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
209
210 cursor.nextObject(function(err, doc) {});
211 cursor.each(function(err, doc) {});
212 cursor.toArray(function(err, docs) {});
213
214 cursor.rewind() // reset the cursor to its initial state.
215
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
216 Useful chainable methods of cursor. These can optionally be options of `find` instead of method calls:
217
218 * `.limit(n).skip(m)` to control paging.
219 * `.sort(fields)` Order by the given fields. There are several equivalent syntaxes:
220 * `.sort({field1: -1, field2: 1})` descending by field1, then ascending by field2.
221 * `.sort([['field1', 'desc'], ['field2', 'asc']])` same as above
222 * `.sort([['field1', 'desc'], 'field2'])` same as above
223 * `.sort('field1')` ascending by field1
224
225 Other options of `find`:
226
227 * `fields` the fields to fetch (to avoid transferring the entire document)
228 * `tailable` if true, makes the cursor [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors).
229 * `batchSize` The number of the subset of results to request the database
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
230 to return for every request. This should initially be greater than 1 otherwise
231 the database will automatically close the cursor. The batch size can be set to 1
232 with `batchSize(n, function(err){})` after performing the initial query to the database.
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
233 * `hint` See [Optimization: hint](http://www.mongodb.org/display/DOCS/Optimization#Optimization-Hint).
234 * `explain` turns this into an explain query. You can also call
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
235 `explain()` on any cursor to fetch the explanation.
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
236 * `snapshot` prevents documents that are updated while the query is active
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
237 from being returned multiple times. See more
238 [details about query snapshots](http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database).
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
239 * `timeout` if false, asks MongoDb not to time out this cursor after an
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
240 inactivity period.
241
242
243 For information on how to create queries, see the
244 [MongoDB section on querying](http://www.mongodb.org/display/DOCS/Querying).
245
246 var mongodb = require('mongodb');
247 var server = new mongodb.Server("127.0.0.1", 27017, {});
248 new mongodb.Db('test', server, {}).open(function (error, client) {
249 if (error) throw error;
250 var collection = new mongodb.Collection(client, 'test_collection');
e4a0fe4 @masylum docs changes
masylum authored
251 collection.find({}, {limit:10}).toArray(function(err, docs) {
252 console.dir(docs);
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
253 });
254 });
255
256 Insert
257 --------
258
259 Signature:
260
261 collection.insert(docs, options, [callback]);
262
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
263 where `docs` can be a single document or an array of documents.
264
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
265 Useful options:
266
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
267 * `safe:true` Should always set if you have a callback.
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
268
269 See also: [MongoDB docs for insert](http://www.mongodb.org/display/DOCS/Inserting).
270
271 var mongodb = require('mongodb');
272 var server = new mongodb.Server("127.0.0.1", 27017, {});
273 new mongodb.Db('test', server, {}).open(function (error, client) {
274 if (error) throw error;
275 var collection = new mongodb.Collection(client, 'test_collection');
276 collection.insert({hello: 'world'}, {safe:true},
277 function(err, objects) {
278 if (err) console.warn(err.message);
279 if (err && err.message.indexOf('E11000 ') !== -1) {
280 // this _id was already inserted in the database
281 }
282 });
283 });
284
285 Note that there's no reason to pass a callback to the insert or update commands
286 unless you use the `safe:true` option. If you don't specify `safe:true`, then
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
287 your callback will be called immediately.
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
288
289 Update; update and insert (upsert)
290 --------
291
292 The update operation will update the first document that matches your query
293 (or all documents that match if you use `multi:true`).
294 If `safe:true`, `upsert` is not set, and no documents match, your callback
295 will be given an error.
296
297 See the [MongoDB docs](http://www.mongodb.org/display/DOCS/Updating) for
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
298 the modifier (`$inc`, `$set`, `$push`, etc.) formats.
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
299
300 Signature:
301
6b23aac @yonran Typos and formatting.
yonran authored
302 collection.update(criteria, objNew, options, [callback]);
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
303
304 Useful options:
305
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
306 * `safe:true` Should always set if you have a callback.
307 * `multi:true` If set, all matching documents are updated, not just the first.
308 * `upsert:true` Atomically inserts the document if no documents matched.
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
309
310 Example for `update`:
311
312 var mongodb = require('mongodb');
313 var server = new mongodb.Server("127.0.0.1", 27017, {});
314 new mongodb.Db('test', server, {}).open(function (error, client) {
315 if (error) throw error;
316 var collection = new mongodb.Collection(client, 'test_collection');
317 collection.update({hi: 'here'}, {$set: {hi: 'there'}}, {safe:true},
318 function(err) {
319 if (err) console.warn(err.message);
320 else console.log('successfully updated');
321 });
322 });
323
324 Find and modify
325 --------
326
327 `findAndModify` is like `update`, but it also gives the updated document to
328 your callback. But there are a few key differences between findAndModify and
329 update:
330
331 1. The signatures differ.
332 2. You can only findAndModify a single item, not multiple items.
333
334 Signature:
335
336 collection.findAndModify(query, sort, update, options, callback)
337
338 The sort parameter is used to specify which object to operate on, if more than
339 one document matches. It takes the same format as the cursor sort (see
340 Connection.find above).
341
342 See the
343 [MongoDB docs for findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command)
344 for more details.
345
346 Useful options:
347
84bafb7 @yonran Updated the readme: made the sorting clearer, added information about C+...
yonran authored
348 * `remove:true` set to a true to remove the object before returning
349 * `new:true` set to true if you want to return the modified object rather than the original. Ignored for remove.
350 * `upsert:true` Atomically inserts the document if no documents matched.
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
351
352 Example for `findAndModify`:
353
354 var mongodb = require('mongodb');
355 var server = new mongodb.Server("127.0.0.1", 27017, {});
356 new mongodb.Db('test', server, {}).open(function (error, client) {
357 if (error) throw error;
358 var collection = new mongodb.Collection(client, 'test_collection');
359 collection.findAndModify({hello: 'world'}, [['_id','asc']], {$set: {hi: 'there'}}, {},
360 function(err, object) {
361 if (err) console.warn(err.message);
362 else console.dir(object); // undefined if no matching object exists.
363 });
364 });
365
366 Save
367 --------
368
369 The `save` method is a shorthand for upsert if the document contains an
370 `_id`, or an insert if there is no `_id`.
371
372 Sponsors
373 ========
374 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.
375
a680bd4 @Poincare made it slightly less easier for spammers to get your email.
Poincare authored
376 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 AT g m a i l.com](mailto:christkv@gmail.com) for details.
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
377
378 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.
379
380 Release Notes
dafa22e @christkv Updated contributors
authored
381 =============
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
382
383 See HISTORY
384
385 Credits
386 ========
387
388 1. [10gen](http://github.com/mongodb/mongo-ruby-driver/)
389 2. [Google Closure Library](http://code.google.com/closure/library/)
390 3. [Jonas Raoni Soares Silva](http://jsfromhell.com/classes/binary-parser)
391
dafa22e @christkv Updated contributors
authored
392 Contributors
393 =============
394
5391007 @christkv Updated contributors
authored
395 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
dafa22e @christkv Updated contributors
authored
396
f71f54f @yonran Added usage and examples to the Readme for all the basic collection meth...
yonran authored
397 License
398 ========
399
400 Copyright 2009 - 2010 Christian Amor Kvalheim.
401
402 Licensed under the Apache License, Version 2.0 (the "License");
403 you may not use this file except in compliance with the License.
404 You may obtain a copy of the License at
405
406 http://www.apache.org/licenses/LICENSE-2.0
407
408 Unless required by applicable law or agreed to in writing, software
409 distributed under the License is distributed on an "AS IS" BASIS,
410 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
411 See the License for the specific language governing permissions and
412 limitations under the License.
413
Something went wrong with that request. Please try again.