Inital Commit
[oweals/finalsclub.git] / node_modules / mongodb / Readme.md
1 Install
2 ========
3
4 Run:
5
6     make
7
8 Community
9 ========
10 Check out the google group http://groups.google.com/group/node-mongodb-native for questions/answers from users of the driver.
11
12 Introduction
13 ========
14
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/.
16
17 A simple example of inserting a document.
18
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) {
22
23             collection.count(function(err, count) {
24               test.assertEquals(1, count);
25             });
26
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);
31
32               // Let's close the db
33               client.close();
34             });
35           });
36         };
37
38     client.open(function(err, p_client) {
39       client.collection('test_insert', test);
40     });
41
42 Important
43 ========
44
45 To enable the driver to use the C/C++ bson parser pass it the option native_parser:true like below
46
47     var client = new Db('integration_tests_20',
48                         new Server("127.0.0.1", 27017),
49                         {native_parser:true});
50
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.
52
53 To access the correct version of BSON objects for your instance do the following
54
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
61
62 GitHub information
63 --------
64
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.
67
68 Once you have the source you can test the driver by running
69
70   $ make test
71
72 in the main directory. You will need to have a mongo instance running on localhost for the integration tests to pass.
73
74 Examples
75 ========
76
77 For examples look in the examples/ directory. You can execute the examples using node.
78
79   $ cd examples
80   $ node queries.js
81
82 GridStore
83 =========
84
85 The GridStore class allows for storage of binary files in mongoDB using the mongoDB defined files and chunks collection definition.
86
87 For more information have a look at [Gridstore](https://github.com/christkv/node-mongodb-native/blob/master/docs/gridfs.md)
88
89 Replicasets
90 ===========
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)
92
93 Notes
94 ========
95
96 The current version does not support connection pooling, but it will be implemented
97 soon.
98
99 Primary Key Factories
100 --------
101
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".
104
105 Simple example below
106
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");
112     }
113
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);
122
123                 // Let's close the db
124                 p_client.close();
125               });
126             });
127           });
128         });
129       });
130     });
131
132 Strict mode
133 --------
134
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.
138
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);
141       
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);
146       });
147
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();
153         });
154       });
155     });
156
157 Documentation
158 ========
159
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.
164
165 Find
166 --------
167
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`.
171
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.
175
176 Signatures:
177
178     collection.find(query, [fields], options);
179
180     cursor.nextObject(function(err, doc) {});
181     cursor.each(function(err, doc) {});
182     cursor.toArray(function(err, docs) {});
183
184     cursor.rewind()  // reset the cursor to its initial state.
185
186 Useful options of `find`:
187
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
207 inactivity period.
208
209
210 For information on how to create queries, see the
211 [MongoDB section on querying](http://www.mongodb.org/display/DOCS/Querying).
212
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) {
219         console.dir(docs);
220       });
221     });
222
223 Insert
224 --------
225
226 Signature:
227
228     collection.insert(docs, options, [callback]);
229
230 Useful options:
231
232 * **`safe:true`** Should always set if you have a callback.
233
234 See also: [MongoDB docs for insert](http://www.mongodb.org/display/DOCS/Inserting).
235
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
246         }
247       });
248     });
249
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")).
254
255 Update; update and insert (upsert)
256 --------
257
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.
262
263 See the [MongoDB docs](http://www.mongodb.org/display/DOCS/Updating) for
264 the modifier (`$inc`, etc.) formats.
265
266 Signature:
267
268     collection.update(criteria, objNew, options, [callback]);
269
270 Useful options:
271
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.
275
276 Example for `update`:
277
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},
284                         function(err) {
285         if (err) console.warn(err.message);
286         else console.log('successfully updated');
287       });
288     });
289
290 Find and modify
291 --------
292
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
295 update:
296
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.
301
302 Signature:
303
304     collection.findAndModify(query, sort, update, options, callback)
305
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).
309
310 See the
311 [MongoDB docs for findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command)
312 for more details.
313
314 Useful options:
315
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.
319
320 Example for `findAndModify`:
321
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.
331       });
332     });
333
334 Find or insert
335 --------
336
337 TODO
338
339 Save
340 --------
341
342 The `save` method is a shorthand for upsert if the document contains an
343 `_id`, or an insert if there is no `_id`.
344
345 Sponsors
346 ========
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.
348
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.
350
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.
352
353 Release Notes
354 =============
355
356 See HISTORY
357
358 Credits
359 ========
360
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)
364
365 Contributors
366 =============
367
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
369
370 License
371 ========
372
373  Copyright 2009 - 2010 Christian Amor Kvalheim.
374
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
378
379        http://www.apache.org/licenses/LICENSE-2.0
380
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.
386