mongo 1.1.1 → 1.1.2
Sign up to get free protection for your applications and to get access to all the features.
- data/LICENSE.txt +1 -13
- data/{README.rdoc → README.md} +113 -151
- data/Rakefile +17 -4
- data/docs/1.0_UPGRADE.md +21 -0
- data/docs/CREDITS.md +119 -0
- data/docs/HISTORY.md +158 -0
- data/docs/TUTORIAL.md +247 -0
- data/lib/mongo.rb +1 -1
- data/lib/mongo/collection.rb +67 -32
- data/lib/mongo/connection.rb +39 -8
- data/lib/mongo/cursor.rb +1 -1
- data/lib/mongo/db.rb +19 -6
- data/lib/mongo/exceptions.rb +3 -0
- data/lib/mongo/gridfs/grid.rb +4 -1
- data/lib/mongo/gridfs/grid_file_system.rb +5 -2
- data/lib/mongo/util/pool.rb +115 -0
- data/mongo.gemspec +4 -5
- data/test/bson/bson_test.rb +3 -1
- data/test/collection_test.rb +30 -0
- data/test/connection_test.rb +65 -52
- data/test/cursor_test.rb +27 -0
- data/test/replica_sets/connect_test.rb +24 -1
- data/test/safe_test.rb +42 -0
- data/test/unit/db_test.rb +2 -0
- data/test/unit/grid_test.rb +49 -0
- data/test/unit/safe_test.rb +125 -0
- metadata +18 -22
- data/HISTORY +0 -215
- data/bin/bson_benchmark.rb +0 -59
- data/bin/fail_if_no_c.rb +0 -11
- data/bin/insert.rb +0 -35
- data/bin/oid.rb +0 -13
- data/examples/admin.rb +0 -43
- data/examples/capped.rb +0 -22
- data/examples/cursor.rb +0 -48
- data/examples/gridfs.rb +0 -44
- data/examples/index_test.rb +0 -126
- data/examples/info.rb +0 -31
- data/examples/queries.rb +0 -70
- data/examples/simple.rb +0 -24
- data/examples/strict.rb +0 -35
- data/examples/types.rb +0 -36
data/Rakefile
CHANGED
@@ -169,7 +169,7 @@ task :ydoc do
|
|
169
169
|
require File.join(File.dirname(__FILE__), 'lib', 'mongo')
|
170
170
|
out = File.join('ydoc', Mongo::VERSION)
|
171
171
|
FileUtils.rm_rf('ydoc')
|
172
|
-
system "yardoc lib/**/*.rb lib/mongo/**/*.rb lib/bson/**/*.rb -e
|
172
|
+
system "yardoc lib/**/*.rb lib/mongo/**/*.rb lib/bson/**/*.rb -e yard/yard_ext.rb -p yard/templates -o #{out} --title MongoRuby-#{Mongo::VERSION} --files docs/TUTORIAL.md,docs/HISTORY.md,docs/CREDITS.md,docs/1.0_UPGRADE.md"
|
173
173
|
end
|
174
174
|
|
175
175
|
namespace :gem do
|
@@ -177,22 +177,35 @@ namespace :gem do
|
|
177
177
|
desc "Install the gem locally"
|
178
178
|
task :install do
|
179
179
|
sh "gem build bson.gemspec"
|
180
|
-
sh "gem install bson-*.gem"
|
180
|
+
sh "gem install --no-rdoc --no-ri bson-*.gem"
|
181
|
+
|
181
182
|
sh "gem build mongo.gemspec"
|
182
|
-
sh "gem install mongo-*.gem"
|
183
|
+
sh "gem install --no-rdoc --no-ri mongo-*.gem"
|
184
|
+
|
183
185
|
sh "rm mongo-*.gem"
|
184
186
|
sh "rm bson-*.gem"
|
185
187
|
end
|
186
188
|
|
187
189
|
desc "Install the optional c extensions"
|
188
190
|
task :install_extensions do
|
191
|
+
sh "gem uninstall -x -a -I bson_ext"
|
189
192
|
sh "gem build bson_ext.gemspec"
|
190
|
-
sh "gem install bson_ext-*.gem"
|
193
|
+
sh "gem install --no-rdoc --no-ri bson_ext-*.gem"
|
191
194
|
sh "rm bson_ext-*.gem"
|
192
195
|
end
|
193
196
|
|
194
197
|
end
|
195
198
|
|
199
|
+
namespace :ci do
|
200
|
+
namespace :test do
|
201
|
+
task :c do
|
202
|
+
Rake::Task['gem:install'].invoke
|
203
|
+
Rake::Task['gem:install_extensions'].invoke
|
204
|
+
Rake::Task['test:c'].invoke
|
205
|
+
end
|
206
|
+
end
|
207
|
+
end
|
208
|
+
|
196
209
|
task :default => :list
|
197
210
|
|
198
211
|
task :list do
|
data/docs/1.0_UPGRADE.md
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
You can upgrade freely from v0.20 to v1.0.
|
2
|
+
|
3
|
+
However, if you're running a version < 0.20, upgrade to 0.20
|
4
|
+
before upgrading to 1.0.
|
5
|
+
|
6
|
+
The upgrade to 0.20 requires some minor code upgrades.
|
7
|
+
|
8
|
+
1. Note the exception changes in HISTORY. Certain exceptions are now scoped under the BSON
|
9
|
+
module; if you're catching these, you will need to modify your code.
|
10
|
+
|
11
|
+
2. The BSON types are now scoped under the BSON module.
|
12
|
+
|
13
|
+
3. Note that mongo_ext no longer exists. The new gems are bson and bson_ext.
|
14
|
+
|
15
|
+
4. Indexes on GridFS chunks collections should be unique. If you have existing GridFS
|
16
|
+
collections, you should drop the current index and replace with a unique one. Before you do this,
|
17
|
+
make sure that index doesn't exist; no need to go through process unnecessarily.
|
18
|
+
If you do need to create the index, once you have the chunks collection, here are the commands you can run:
|
19
|
+
|
20
|
+
@chunks.drop_index('files_id_1_n_1')
|
21
|
+
@chunks.create_index([['files_id', Mongo::ASCENDING], ['n', Mongo::ASCENDING]], :unique => true)
|
data/docs/CREDITS.md
ADDED
@@ -0,0 +1,119 @@
|
|
1
|
+
# Credits
|
2
|
+
|
3
|
+
Adrian Madrid, aemadrid@gmail.com
|
4
|
+
|
5
|
+
* bin/mongo_console
|
6
|
+
* examples/benchmarks.rb
|
7
|
+
* examples/irb.rb
|
8
|
+
* Modifications to examples/simple.rb
|
9
|
+
* Found plenty of bugs and missing features.
|
10
|
+
* Ruby 1.9 support.
|
11
|
+
* Gem support.
|
12
|
+
* Many other code suggestions and improvements.
|
13
|
+
|
14
|
+
Aman Gupta, aman@tmm1.net
|
15
|
+
|
16
|
+
* Collection#save
|
17
|
+
* Noted bug in returning query batch size.
|
18
|
+
|
19
|
+
Jon Crosby, jon@joncrosby.me
|
20
|
+
|
21
|
+
* Some code clean-up
|
22
|
+
|
23
|
+
John Nunemaker, http://railstips.org
|
24
|
+
|
25
|
+
* Collection#create_index takes symbols as well as strings
|
26
|
+
* Fix for Collection#save
|
27
|
+
* Add logger convenience methods to connection and database
|
28
|
+
|
29
|
+
David James, djames@sunlightfoundation.com
|
30
|
+
|
31
|
+
* Fix dates to return as UTC
|
32
|
+
|
33
|
+
Paul Dlug, paul.dlug@gmail.com
|
34
|
+
|
35
|
+
* Generate _id on the client side if not provided
|
36
|
+
* Collection#insert and Collection#save return _id
|
37
|
+
|
38
|
+
Durran Jordan, durran@gmail.com
|
39
|
+
|
40
|
+
* DB#collections
|
41
|
+
* Support for specifying sort order as array of [key, direction] pairs
|
42
|
+
* OrderedHash#update aliases to merge!
|
43
|
+
|
44
|
+
Cyril Mougel, cyril.mougel@gmail.com
|
45
|
+
|
46
|
+
* Initial logging support
|
47
|
+
* Test case
|
48
|
+
|
49
|
+
Jack Chen, chendo on github
|
50
|
+
|
51
|
+
* Test case + fix for deserializing pre-epoch Time instances
|
52
|
+
|
53
|
+
Michael Bernstein, mrb on github
|
54
|
+
|
55
|
+
* Cursor#sort
|
56
|
+
|
57
|
+
Paulo Ahahgon, pahagon on github
|
58
|
+
|
59
|
+
* removed hard limit
|
60
|
+
|
61
|
+
Les Hill, leshill on github
|
62
|
+
|
63
|
+
* OrderedHash#each returns self
|
64
|
+
|
65
|
+
Sean Cribbs, seancribbs on github
|
66
|
+
|
67
|
+
* Modified standard_benchmark to allow profiling
|
68
|
+
* C ext for faster ObjectID creation
|
69
|
+
|
70
|
+
Sunny Hirai
|
71
|
+
|
72
|
+
* Suggested hashcode fix for Mongo::ObjectID
|
73
|
+
* Noted index ordering bug.
|
74
|
+
* GridFS performance boost
|
75
|
+
|
76
|
+
Christos Trochalakis
|
77
|
+
|
78
|
+
* Added map/reduce helper
|
79
|
+
|
80
|
+
Blythe Dunham
|
81
|
+
|
82
|
+
* Added finalize option to map/reduce
|
83
|
+
|
84
|
+
Matt Powell (fauxparse)
|
85
|
+
|
86
|
+
* Added GridStore#mv
|
87
|
+
|
88
|
+
Patrick Collison
|
89
|
+
|
90
|
+
* Added safe mode for Collection#remove
|
91
|
+
|
92
|
+
Chuck Remes
|
93
|
+
|
94
|
+
* Extraction of BSON into separate gems
|
95
|
+
* Extensions compile on Rubinius
|
96
|
+
* Performance improvements for INT in C extensions
|
97
|
+
* Performance improvements for JRuby BSON encoder and callback classes
|
98
|
+
|
99
|
+
Dmitrii Golub (Houdini) and Jacques Crocker (railsjedi)
|
100
|
+
|
101
|
+
* Support open to exclude fields on query
|
102
|
+
|
103
|
+
dfitzgibbon
|
104
|
+
|
105
|
+
* patch for ensuring bson_ext compatibility with early release of Ruby 1.8.5
|
106
|
+
|
107
|
+
Matt Taylor
|
108
|
+
|
109
|
+
* Noticed excessive calls to ObjectId#to_s. As a result, stopped creating
|
110
|
+
log messages when no logger was passed to Mongo::Connection. Resulted in a significant
|
111
|
+
performance improvement.
|
112
|
+
|
113
|
+
Hongli Lai (Phusion)
|
114
|
+
|
115
|
+
* Significant performance improvements. See commits.
|
116
|
+
|
117
|
+
Mislav Marohnić
|
118
|
+
|
119
|
+
* Replaced returning with each_with_object
|
data/docs/HISTORY.md
ADDED
@@ -0,0 +1,158 @@
|
|
1
|
+
# MongoDB Ruby Driver History
|
2
|
+
|
3
|
+
### 1.1.2
|
4
|
+
2010-11-4
|
5
|
+
|
6
|
+
* Two critical fixes to automated failover and replica sets.
|
7
|
+
* Bug passing :timeout to Cursor.
|
8
|
+
* Permit safe mode specification on Connection, Collection, and DB levels.
|
9
|
+
* Specify replica set name on connect to verify connection to the right set.
|
10
|
+
* Misc. reorganization of project and docs.
|
11
|
+
|
12
|
+
### 1.1.1
|
13
|
+
2010-10-14
|
14
|
+
|
15
|
+
* Several critical JRuby bug fixes
|
16
|
+
* Fixes for JRuby in 1.9 mode
|
17
|
+
* Check keys and move id only when necessary for JRuby encoder
|
18
|
+
|
19
|
+
## 1.1
|
20
|
+
2010-10-4
|
21
|
+
|
22
|
+
* Official JRuby support via Java extensons for BSON (beta)
|
23
|
+
* Connection#lock! and Connection#unlock! for easy fsync lock
|
24
|
+
* Note: BSON::Code is no longer a subclass of String.
|
25
|
+
|
26
|
+
### 1.0.9
|
27
|
+
2010-9-20
|
28
|
+
|
29
|
+
* Significant performance improvements (with a lot of help from Hongli Lai)
|
30
|
+
|
31
|
+
### 1.0.8
|
32
|
+
2010-8-27
|
33
|
+
|
34
|
+
* Cursor#rewind! and more consistent Cursor Enumberable behavior
|
35
|
+
* Deprecated ObjectID for ObjectId
|
36
|
+
* Numerous minor bug fixes.
|
37
|
+
|
38
|
+
### 1.0.7
|
39
|
+
2010-8-4
|
40
|
+
|
41
|
+
* A few minor test/doc fixes.
|
42
|
+
* Better tests for replica sets and replication acknowledgment.
|
43
|
+
* Deprecated DB#error and DB#last_status
|
44
|
+
|
45
|
+
### 1.0.6
|
46
|
+
2010-7-26
|
47
|
+
|
48
|
+
* Replica set support.
|
49
|
+
* Collection#map_reduce bug fix.
|
50
|
+
|
51
|
+
### 1.0.5
|
52
|
+
2010-7-13
|
53
|
+
|
54
|
+
* Fix for bug introduced in 1.0.4.
|
55
|
+
|
56
|
+
### 1.0.4
|
57
|
+
2010-7-13
|
58
|
+
|
59
|
+
* Removed deprecated
|
60
|
+
* Cursor admin option
|
61
|
+
* DB#query
|
62
|
+
* DB#create_index (use Collection#create_index)
|
63
|
+
* DB#command only takes hash options now
|
64
|
+
* j2bson executable (neomantra)
|
65
|
+
* Fixed bson_ext compilation on Solaris (slyphon)
|
66
|
+
* System JS helpers (neovintage)
|
67
|
+
* Use one mutex per thread on pooled connections (cremes)
|
68
|
+
* Check for CursorNotFound response flag
|
69
|
+
* MapReduce can return raw command output using :raw
|
70
|
+
* BSON::OrderedHash equality with other Ruby hashes (Ryan Angilly)
|
71
|
+
* Fix for broken Socket.send with large payloads (Frédéric De Jaeger)
|
72
|
+
* Lots of minor improvements. See commmits.
|
73
|
+
|
74
|
+
### 1.0.3
|
75
|
+
2010-6-15
|
76
|
+
|
77
|
+
* Optimiztion for BSON::OrderedHash
|
78
|
+
* Some important fixes.
|
79
|
+
|
80
|
+
### 1.0.2
|
81
|
+
2010-6-5
|
82
|
+
|
83
|
+
This is a minor release for fixing an incompatibility with MongoDB v1.5.2
|
84
|
+
|
85
|
+
* Fix for boolean response on commands for core server v1.5.2
|
86
|
+
* BSON.read_bson_document and b2json executable (neomantra)
|
87
|
+
* BSON::ObjectID() shortcut for BSON::ObjectID.from_string (tmm1)
|
88
|
+
* Various bug fixes.
|
89
|
+
|
90
|
+
### 1.0.1
|
91
|
+
2010-5-7
|
92
|
+
|
93
|
+
* set Encoding.default_internal
|
94
|
+
* DEPRECATE JavaScript string on Collection#find. You now must specify $where explicitly.
|
95
|
+
* Added Grid#exist? and GridFileSystem#exist?
|
96
|
+
* Support for replication acknowledgment
|
97
|
+
* Support for $slice
|
98
|
+
* Namespaced OrderedHash under BSON (sleverbor)
|
99
|
+
|
100
|
+
## 1.0
|
101
|
+
2010-4-29
|
102
|
+
Note: if upgrading from versions prior to 0.20, be sure to upgrade
|
103
|
+
to 0.20 before upgrading to 1.0.
|
104
|
+
|
105
|
+
* Inspected ObjectID is represented in MongoDB extended json format.
|
106
|
+
* Support for tailable cursors.
|
107
|
+
* Configurable query response batch size (thx. to Aman Gupta)
|
108
|
+
|
109
|
+
* bson_ext installs on early release of Ruby 1.8.5 (dfitzgibbon)
|
110
|
+
* Deprecated DB#create_index. Use Collection#create_index index.
|
111
|
+
* Removed deprecated Grid#put syntax; no longer requires a filename.
|
112
|
+
|
113
|
+
### 0.20.1
|
114
|
+
2010-4-7
|
115
|
+
|
116
|
+
* Added bson gem dependency.
|
117
|
+
|
118
|
+
### 0.20
|
119
|
+
2010-4-7
|
120
|
+
|
121
|
+
If upgrading from a previous version of the Ruby driver, please read these notes carefully,
|
122
|
+
along with the 0.20_UPGRADE doc.
|
123
|
+
|
124
|
+
* Support for new commands:
|
125
|
+
* Collection#find_and_modify
|
126
|
+
* Collection#stats
|
127
|
+
* DB#stats
|
128
|
+
* Query :fields options allows for values of 0 to exclude fields (houdini, railsjedi).
|
129
|
+
* GridFS
|
130
|
+
* Option to delete old versions of GridFileSystem entries.
|
131
|
+
* Filename is now optional for Grid#put.
|
132
|
+
* Option to write arbitrary attributes to a file: @grid.put(@data, :favorite_phrase => "blimey!")
|
133
|
+
* Indexes created on the chunks collection are now unique. If you have an existing chunks collection,
|
134
|
+
you may want to remove
|
135
|
+
* Removed the following deprecated items:
|
136
|
+
* GridStore class
|
137
|
+
* RegexpOfHolding class
|
138
|
+
* Paired connections must now be initialized with Connection.paired
|
139
|
+
|
140
|
+
* BSON-related code extracted into two separate gems: bson and bson_ext (thx to Chuck Remes).
|
141
|
+
* mongo_ext no longer exists.
|
142
|
+
* BSON::Binary constructor can now take a string, which will be packed into an array.
|
143
|
+
* Exception class adjustments:
|
144
|
+
* Mongo::InvalidObjectID moved to BSON::InvalidObjectID
|
145
|
+
* Mongo::InvalidDocument moved to BSON::InvalidDocument
|
146
|
+
* Mongo::InvalidStringEncoding moved to BSON::InvalidStringEncoding
|
147
|
+
* Mongo::InvalidName replaced by Mongo::InvalidNSName and BSON::InvalidKeyName
|
148
|
+
* BSON types are now namespaced under the BSON module. These types include:
|
149
|
+
* Binary
|
150
|
+
* ObjectID
|
151
|
+
* Code
|
152
|
+
* DBRef
|
153
|
+
* MinKey and MaxKey
|
154
|
+
* Extensions compile on Rubinius (Chuck Remes).
|
155
|
+
|
156
|
+
## Prior to 0.20
|
157
|
+
|
158
|
+
See git revisions.
|
data/docs/TUTORIAL.md
ADDED
@@ -0,0 +1,247 @@
|
|
1
|
+
# MongoDB Ruby Driver Tutorial
|
2
|
+
|
3
|
+
This tutorial gives many common examples of using MongoDB with the Ruby driver. If you're looking for information on data modeling, see [MongoDB Data Modeling and Rails](http://www.mongodb.org/display/DOCS/MongoDB+Data+Modeling+and+Rails). Links to the various object mappers are listed on our [object mappers page](http://www.mongodb.org/display/DOCS/Object+Mappers+for+Ruby+and+MongoDB).
|
4
|
+
|
5
|
+
Interested in GridFS? See [GridFS in Ruby](http://www.mongodb.org/display/DOCS/GridFS+in+Ruby).
|
6
|
+
|
7
|
+
As always, the [latest source for the Ruby driver](http://github.com/mongodb/mongo-ruby-driver) can be found on [github](http://github.com/mongodb/mongo-ruby-driver/).
|
8
|
+
|
9
|
+
## Installation
|
10
|
+
|
11
|
+
The mongo-ruby-driver gem is served through Rubygems.org. To install, make sure you have the latest version of rubygems.
|
12
|
+
gem update --system
|
13
|
+
Next, install the mongo rubygem:
|
14
|
+
gem install mongo
|
15
|
+
|
16
|
+
The required `bson` gem will be installed automatically.
|
17
|
+
|
18
|
+
For optimum performance, install the bson_ext gem:
|
19
|
+
|
20
|
+
gem install bson_ext
|
21
|
+
|
22
|
+
After installing, you may want to look at the [examples](http://github.com/mongodb/mongo-ruby-driver/tree/master/examples) directory included in the source distribution. These examples walk through some of the basics of using the Ruby driver.
|
23
|
+
|
24
|
+
## Getting started
|
25
|
+
|
26
|
+
#### Using the gem
|
27
|
+
|
28
|
+
All of the code here assumes that you have already executed the following Ruby code:
|
29
|
+
|
30
|
+
require 'rubygems' # not necessary for Ruby 1.9
|
31
|
+
require 'mongo'
|
32
|
+
|
33
|
+
#### Making a Connection
|
34
|
+
|
35
|
+
An `Mongo::Connection` instance represents a connection to MongoDB. You use a Connection instance to obtain an Mongo:DB instance, which represents a named database. The database doesn't have to exist - if it doesn't, MongoDB will create it for you.
|
36
|
+
|
37
|
+
You can optionally specify the MongoDB server address and port when connecting. The following example shows three ways to connect to the database "mydb" on the local machine:
|
38
|
+
|
39
|
+
db = Mongo::Connection.new.db("mydb")
|
40
|
+
db = Mongo::Connection.new("localhost").db("mydb")
|
41
|
+
db = Mongo::Connection.new("localhost", 27017).db("mydb")
|
42
|
+
|
43
|
+
At this point, the `db` object will be a connection to a MongoDB server for the specified database. Each DB instance uses a separate socket connection to the server.
|
44
|
+
|
45
|
+
If you're trying to connect to a replica set, see [Replica Sets in Ruby](http://www.mongodb.org/display/DOCS/Replica+Sets+in+Ruby).
|
46
|
+
|
47
|
+
#### Listing All Databases
|
48
|
+
|
49
|
+
connection = Mongo::Connection.new # (optional host/port args)
|
50
|
+
connection.database_names.each { |name| puts name }
|
51
|
+
connection.database_info.each { |info| puts info.inspect}
|
52
|
+
|
53
|
+
#### Dropping a Database
|
54
|
+
connection.drop_database('database_name')
|
55
|
+
|
56
|
+
MongoDB can be run in a secure mode where access to databases is controlled through name and password authentication. When run in this mode, any client application must provide a name and password before doing any operations. In the Ruby driver, you simply do the following with the connected mongo object:
|
57
|
+
|
58
|
+
auth = db.authenticate(my_user_name, my_password)
|
59
|
+
|
60
|
+
If the name and password are valid for the database, `auth` will be `true`. Otherwise, it will be `false`. You should look at the MongoDB log for further information if available.
|
61
|
+
|
62
|
+
#### Getting a List Of Collections
|
63
|
+
|
64
|
+
Each database has zero or more collections. You can retrieve a list of them from the db (and print out any that are there):
|
65
|
+
|
66
|
+
db.collection_names.each { |name| puts name }
|
67
|
+
|
68
|
+
and assuming that there are two collections, name and address, in the database, you would see
|
69
|
+
|
70
|
+
name
|
71
|
+
address
|
72
|
+
|
73
|
+
as the output.
|
74
|
+
|
75
|
+
#### Getting a Collection
|
76
|
+
|
77
|
+
You can get a collection to use using the `collection` method:
|
78
|
+
coll = db.collection("testCollection")
|
79
|
+
This is aliased to the \[\] method:
|
80
|
+
coll = db["testCollection"]
|
81
|
+
|
82
|
+
Once you have this collection object, you can now do things like insert data, query for data, etc.
|
83
|
+
|
84
|
+
#### Inserting a Document
|
85
|
+
|
86
|
+
Once you have the collection object, you can insert documents into the collection. For example, lets make a little document that in JSON would be represented as
|
87
|
+
|
88
|
+
{
|
89
|
+
"name" : "MongoDB",
|
90
|
+
"type" : "database",
|
91
|
+
"count" : 1,
|
92
|
+
"info" : {
|
93
|
+
x : 203,
|
94
|
+
y : 102
|
95
|
+
}
|
96
|
+
}
|
97
|
+
|
98
|
+
Notice that the above has an "inner" document embedded within it. To do this, we can use a Hash or the driver's OrderedHash (which preserves key order) to create the document (including the inner document), and then just simply insert it into the collection using the `insert()` method.
|
99
|
+
|
100
|
+
doc = {"name" => "MongoDB", "type" => "database", "count" => 1,
|
101
|
+
"info" => {"x" => 203, "y" => '102'`
|
102
|
+
coll.insert(doc)
|
103
|
+
|
104
|
+
#### Updating a Document
|
105
|
+
|
106
|
+
We can update the previous document using the `update` method. There are a couple ways to update a document. We can rewrite it:
|
107
|
+
|
108
|
+
doc["name"] = "MongoDB Ruby"
|
109
|
+
coll.update({"_id" => doc["_id"]}, doc)
|
110
|
+
|
111
|
+
Or we can use an atomic operator to change a single value:
|
112
|
+
|
113
|
+
coll.update({"_id" => doc["_id"]}, {"$set" => {"name" => "MongoDB Ruby"`)
|
114
|
+
|
115
|
+
Read [more about updating documents|Updating].
|
116
|
+
|
117
|
+
#### Finding the First Document In a Collection using `find_one()`
|
118
|
+
|
119
|
+
To show that the document we inserted in the previous step is there, we can do a simple `find_one()` operation to get the first document in the collection. This method returns a single document (rather than the `Cursor` that the `find()` operation returns).
|
120
|
+
|
121
|
+
my_doc = coll.find_one()
|
122
|
+
puts my_doc.inspect
|
123
|
+
|
124
|
+
and you should see:
|
125
|
+
|
126
|
+
{"_id"=>#<BSON::ObjectID:0x118576c ...>, "name"=>"MongoDB",
|
127
|
+
"info"=>{"x"=>203, "y"=>102}, "type"=>"database", "count"=>1}
|
128
|
+
|
129
|
+
Note the `\_id` element has been added automatically by MongoDB to your document.
|
130
|
+
|
131
|
+
#### Adding Multiple Documents
|
132
|
+
|
133
|
+
To demonstrate some more interesting queries, let's add multiple simple documents to the collection. These documents will have the following form:
|
134
|
+
{
|
135
|
+
"i" : value
|
136
|
+
}
|
137
|
+
|
138
|
+
Here's how to insert them:
|
139
|
+
|
140
|
+
100.times { |i| coll.insert("i" => i) }
|
141
|
+
|
142
|
+
Notice that we can insert documents of different "shapes" into the same collection. These records are in the same collection as the complex record we inserted above. This aspect is what we mean when we say that MongoDB is "schema-free".
|
143
|
+
|
144
|
+
#### Counting Documents in a Collection
|
145
|
+
|
146
|
+
Now that we've inserted 101 documents (the 100 we did in the loop, plus the first one), we can check to see if we have them all using the `count()` method.
|
147
|
+
|
148
|
+
puts coll.count()
|
149
|
+
|
150
|
+
and it should print `101`.
|
151
|
+
|
152
|
+
#### Using a Cursor to get all of the Documents
|
153
|
+
|
154
|
+
To get all the documents from the collection, we use the `find()` method. `find()` returns a `Cursor` object, which allows us to iterate over the set of documents that matches our query. The Ruby driver's Cursor implemented Enumerable, which allows us to use `Enumerable#each`, `Enumerable#map}, etc. For instance:
|
155
|
+
|
156
|
+
coll.find().each { |row| puts row.inspect }
|
157
|
+
|
158
|
+
and that should print all 101 documents in the collection.
|
159
|
+
|
160
|
+
#### Getting a Single Document with a Query
|
161
|
+
|
162
|
+
We can create a _query_ hash to pass to the `find()` method to get a subset of the documents in our collection. For example, if we wanted to find the document for which the value of the "i" field is 71, we would do the following ;
|
163
|
+
|
164
|
+
coll.find("i" => 71).each { |row| puts row.inspect }
|
165
|
+
|
166
|
+
and it should just print just one document:
|
167
|
+
|
168
|
+
{"_id"=>#<BSON::ObjectID:0x117de90 ...>, "i"=>71}
|
169
|
+
|
170
|
+
#### Getting a Set of Documents With a Query
|
171
|
+
|
172
|
+
We can use the query to get a set of documents from our collection. For example, if we wanted to get all documents where "i" > 50, we could write:
|
173
|
+
|
174
|
+
coll.find("i" => {"$gt" => 50}).each { |row| puts row }
|
175
|
+
|
176
|
+
which should print the documents where i > 50. We could also get a range, say 20 < i <= 30:
|
177
|
+
|
178
|
+
coll.find("i" => {"$gt" => 20, "$lte" => 30}).each { |row| puts row }
|
179
|
+
|
180
|
+
#### Selecting a subset of fields for a query
|
181
|
+
|
182
|
+
Use the `:fields` option. If you just want fields "a" and "b":
|
183
|
+
|
184
|
+
coll.find("i" => {"$gt" => 50}, :fields => ["a", "b"]).each { |row| puts row }
|
185
|
+
|
186
|
+
#### Querying with Regular Expressions
|
187
|
+
|
188
|
+
Regular expressions can be used to query MongoDB. To find all names that begin with 'a':
|
189
|
+
|
190
|
+
coll.find({"name" => /^a/})
|
191
|
+
|
192
|
+
You can also construct a regular expression dynamically. To match a given search string:
|
193
|
+
|
194
|
+
search_string = params['search']
|
195
|
+
|
196
|
+
# Constructor syntax
|
197
|
+
coll.find({"name" => Regexp.new(search_string)})
|
198
|
+
|
199
|
+
# Literal syntax
|
200
|
+
coll.find({"name" => /#{search_string}/})
|
201
|
+
|
202
|
+
Although MongoDB isn't vulnerable to anything like SQL-injection, it may be worth checking the search string for anything malicious.
|
203
|
+
|
204
|
+
## Indexing
|
205
|
+
|
206
|
+
#### Creating An Index
|
207
|
+
|
208
|
+
MongoDB supports indexes, and they are very easy to add on a collection. To create an index, you specify an index name and an array of field names to be indexed, or a single field name. The following creates an ascending index on the "i" field:
|
209
|
+
|
210
|
+
# create_index assumes ascending order; see method docs
|
211
|
+
# for details
|
212
|
+
coll.create_index("i")
|
213
|
+
To specify complex indexes or a descending index you need to use a slightly more complex syntax - the index specifier must be an Array of [field name, direction] pairs. Directions should be specified as Mongo::ASCENDING or Mongo::DESCENDING:
|
214
|
+
|
215
|
+
# Explicit "ascending"
|
216
|
+
coll.create_index([["i", Mongo::ASCENDING]])
|
217
|
+
|
218
|
+
#### Creating and querying on a geospatial index
|
219
|
+
|
220
|
+
First, create the index on a field containing long-lat values:
|
221
|
+
|
222
|
+
people.create_index([["loc", Mongo::GEO2D]])
|
223
|
+
|
224
|
+
Then get a list of the twenty locations nearest to the point 50, 50:
|
225
|
+
|
226
|
+
people.find({"loc" => {"$near" => [50, 50]}}, {:limit => 20}).each do |p|
|
227
|
+
puts p.inspect
|
228
|
+
end
|
229
|
+
|
230
|
+
#### Getting a List of Indexes on a Collection
|
231
|
+
|
232
|
+
You can get a list of the indexes on a collection using `coll.index_information()`.
|
233
|
+
|
234
|
+
## Database Administration
|
235
|
+
|
236
|
+
A database can have one of three profiling levels: off (:off), slow queries only (:slow_only), or all (:all). To see the database level:
|
237
|
+
|
238
|
+
puts db.profiling_level # => off (the symbol :off printed as a string)
|
239
|
+
db.profiling_level = :slow_only
|
240
|
+
|
241
|
+
Validating a collection will return an interesting hash if all is well or raise an exception if there is a problem.
|
242
|
+
p db.validate_collection('coll_name')
|
243
|
+
|
244
|
+
## See Also
|
245
|
+
|
246
|
+
* [MongoDB Koans](http://github.com/chicagoruby/MongoDB_Koans) A path to MongoDB enlightenment via the Ruby driver.
|
247
|
+
* [MongoDB Manual](http://www.mongodb.org/display/DOCS/Developer+Zone)
|