Options Hash (opts):

Set the default safe-mode options for insert, update, and remove method
called on this Collection instance. If no value is provided, the default
value set on this instance’s DB will be used. This default can be
overridden for any invocation of insert, update, or remove.

Core docs:

# File 'lib/mongo/collection.rb', line 47definitialize(name,db,opts={})ifdb.is_a?(String)&&name.is_a?(Mongo::DB)warn"Warning: the order of parameters to initialize a collection have changed. "+"Please specify the collection name first, followed by the db."db,name=name,dbendcasenamewhenSymbol,StringelseraiseTypeError,"new_name must be a string or symbol"endname=name.to_sifname.empty?orname.include?".."raiseMongo::InvalidNSName,"collection names cannot be empty"endifname.include?"$"raiseMongo::InvalidNSName,"collection names must not contain '$'"unlessname=~/((^\$cmd)|(oplog\.\$main))/endifname.match(/^\./)orname.match(/\.$/)raiseMongo::InvalidNSName,"collection names must not start or end with '.'"endifopts.respond_to?(:create_pk)||!opts.is_a?(Hash)warn"The method for specifying a primary key factory on a Collection has changed.\n"+"Please specify it as an option (e.g., :pk => PkFactory)."pk_factory=optselsepk_factory=nilend@db,@name=db,name@connection=@db.connection@cache_time=@db.cache_time@cache=Hash.new(0)unlesspk_factory@safe=opts.fetch(:safe,@db.safe)end@pk_factory=pk_factory||opts[:pk]||BSON::ObjectId@hint=nilend

Examples:

Creating a compound index:

Creating a geospatial index:

@restaurants.create_index([['location',Mongo::GEO2D]])# Note that this will work only if 'location' represents x,y coordinates:{'location':[0,50]}{'location':{'x'=>0,'y'=>50}}{'location':{'latitude'=>0,'longitude'=>50}}

Parameters:

Note that geospatial indexing only works with versions of MongoDB >=
1.3.3+. Keep in mind, too, that in order to geo-index a given field, that
field must reference either an array or a sub-object where the first two
values represent x- and y-coordinates. Examples can be seen below.

Also note that it is permissible to create compound indexes that include a
geospatial index as long as the geospatial index comes first.

If your code calls create_index frequently, you can use
Collection#ensure_index to cache these calls and thereby prevent excessive
round trips to the database.

Return a list of distinct values for key across all documents in
the collection. The key may use dot notation to reach into an embedded
object.

Examples:

Saving zip codes and ages and returning distinct results.

@collection.save({:zip=>10010,:name=>{:age=>27}})@collection.save({:zip=>94108,:name=>{:age=>24}})@collection.save({:zip=>10010,:name=>{:age=>27}})@collection.save({:zip=>99701,:name=>{:age=>24}})@collection.save({:zip=>94108,:name=>{:age=>27}})@collection.distinct(:zip)[10010,94108,99701]@collection.distinct("name.age")[27,24]# You may also pass a document selector as the second parameter# to limit the documents over which distinct is run:@collection.distinct("name.age",{"name.age"=>{"$gt"=>24}})[27]

Calls create_index and sets a flag to not do so again for another X
minutes. this time can be specified as an option when initializing a
Mongo::DB object as options[:cache_time] Any changes to an index will be
propogated through regardless of cache time (e.g., a change of index
direction)

The parameters and options for this methods are the same as those for
Collection#create_index.

Returns:

# File 'lib/mongo/collection.rb', line 448defensure_index(spec,opts={})now=Time.now.utc.to_ifield_spec=parse_index_spec(spec)name=opts.delete(:name)||generate_index_name(field_spec)name=name.to_sifnameif!@cache[name]||@cache[name]<=nowgenerate_indexes(field_spec,name,opts)end# Reset the cache here in case there are any errors inserting. Best to be safe.@cache[name]=now+@cache_timenameend

The selector argument is a prototype document that all results
must match. For example:

collection.find({"hello"=>"world"})

only matches documents that have a key "hello" with value
"world". Matches can have other keys *in addition* to
"hello".

If given an optional block find will yield a Cursor to that block,
close the cursor, and then return nil. This guarantees that partially
evaluated cursors will be closed. If given no block find returns a
cursor.

Parameters:

a document specifying elements which must be present for a document to be
included in the result set. Note that in rare cases, (e.g., with $near
queries), the order of keys will matter. To preserve key order on a
selector, use an instance of BSON::OrderedHash (only applies to Ruby 1.8).

Options Hash (opts):

field names that should be returned in the result set ("_id" will
be included unless explicity excluded). By limiting results to a certain
subset of fields, you can cut down on network traffic and decoding time. If
using a Hash, keys should be field names and values should be either 1 or
0, depending on whether you want to include or exclude the given field.

hint for query optimizer, usually not necessary if using MongoDB > 1.1

(Boolean):snapshot
— default:
false
—

if true, snapshot mode will be used for this query. Snapshot mode assures
no duplicates are returned, or objects missed, which were preset at both
the start and end of the query’s execution. For details see
http://www.mongodb.org/display/DOCS/How+to+do+Snapshotting+in+the+Mongo+Database

(Boolean):batch_size
— default:
100
—

the number of documents to returned by the database per GETMORE operation.
A value of 0 will let the database server decide how many results to
returns. This option can be ignored for most use cases.

(Boolean):timeout
— default:
true
—

when true, the returned cursor will be subject to the normal
cursor timeout behavior of the mongod process. When false, the
returned cursor will never timeout. Note that disabling timeout will only
work when #find is invoked with a block. This is to prevent any inadvertant
failure to close the cursor, as the cursor is explicitly closed when block
code finishes.

Raises:

(ArgumentError)
—

if timeout is set to false and find is not invoked in a block

(RuntimeError)
—

if given unknown options

Core docs:

# File 'lib/mongo/collection.rb', line 168deffind(selector={},opts={})fields=opts.delete(:fields)fields=["_id"]iffields&&fields.empty?skip=opts.delete(:skip)||skip||0limit=opts.delete(:limit)||0sort=opts.delete(:sort)hint=opts.delete(:hint)snapshot=opts.delete(:snapshot)batch_size=opts.delete(:batch_size)timeout=(opts.delete(:timeout)==false)?false:trueiftimeout==false&&!block_given?raiseArgumentError,"Collection#find must be invoked with a block when timeout is disabled."endifhinthint=normalize_hint_fields(hint)elsehint=@hint# assumed to be normalized alreadyendraiseRuntimeError,"Unknown options [#{opts.inspect}]"unlessopts.empty?cursor=Cursor.new(self,:selector=>selector,:fields=>fields,:skip=>skip,:limit=>limit,:order=>sort,:hint=>hint,:snapshot=>snapshot,:timeout=>timeout,:batch_size=>batch_size)ifblock_given?yieldcursorcursor.closenilelsecursorendend

specify a sort option for the query using any of the sort options available
for Cursor#sort. Sort order is important if the query will be matching
multiple documents since only the first matching document will be updated
and returned.

(Boolean):remove
— default:
false
—

If true, removes the the returned document from the collection.

(Boolean):new
— default:
false
—

If true, returns the updated document; otherwise, returns the document
prior to update.

Parameters:

a hash specifying elements which must be present for a document to be
included in the result set or an instance of ObjectId to be used as the
value for an _id query. If nil, an empty selector, {}, will be used.

Options Hash (opts):

Returns:

(OrderedHash, Nil)
—

a single document or nil if no result is found.

Raises:

(TypeError)
—

if the argument is of an improper type.

218
219
220
221
222
223
224
225
226
227
228
229
230

# File 'lib/mongo/collection.rb', line 218deffind_one(spec_or_object_id=nil,opts={})spec=casespec_or_object_idwhennil{}whenBSON::ObjectId{:_id=>spec_or_object_id}whenHashspec_or_object_idelseraiseTypeError,"spec_or_object_id must be an instance of ObjectId or Hash, or nil"endfind(spec,opts.merge(:limit=>-1)).next_documentend

# File 'lib/mongo/collection.rb', line 585defgroup(opts,condition={},initial={},reduce=nil,finalize=nil)ifopts.is_a?(Hash)returnnew_group(opts)elsewarn"Collection#group no longer take a list of parameters. This usage is deprecated."+"Check out the new API at http://api.mongodb.org/ruby/current/Mongo/Collection.html#group-instance_method"endreduce=BSON::Code.new(reduce)unlessreduce.is_a?(BSON::Code)group_command={"group"=>{"ns"=>@name,"$reduce"=>reduce,"cond"=>condition,"initial"=>initial}}ifopts.is_a?(Symbol)raiseMongoArgumentError,"Group takes either an array of fields to group by or a JavaScript function"+"in the form of a String or BSON::Code."endunlessopts.nil?ifopts.is_a?Arraykey_type="key"key_value={}opts.each{|k|key_value[k]=1}elsekey_type="$keyf"key_value=opts.is_a?(BSON::Code)?opts:BSON::Code.new(opts)endgroup_command["group"][key_type]=key_valueendfinalize=BSON::Code.new(finalize)iffinalize.is_a?(String)iffinalize.is_a?(BSON::Code)group_command['group']['finalize']=finalizeendresult=@db.command(group_command)ifMongo::Support.ok?(result)result["retval"]elseraiseOperationFailure,"group command failed: #{result['errmsg']}"endend

Options Hash (opts):

run the operation in safe mode, which run a getlasterror command on the
database to report any assertion. In addition, a hash can be provided to
run an fsync and/or wait for replication of the insert (>= 1.5.1). Safe
options provided here will override any safe options set on this
collection, its database object, or the current connection. See the options
on for DB#get_last_error.

Returns:

(ObjectId, Array)
—

The _id of the inserted document or a list of _ids of all inserted
documents.

a valid output type. In versions of MongoDB prior to v1.7.6, this option
takes the name of a collection for the output results. In versions 1.7.6
and later, this option specifies the output type. See the core docs for
available output types.

(Boolean):keeptemp
— default:
false
—

if true, the generated collection will be persisted. The defualt is false.
Note that this option has no effect is versions of MongoDB > v1.7.6.

(Boolean):verbose
— default:
false
—

if true, provides statistics on job execution time.

(Boolean):raw
— default:
false
—

if true, return the raw result object from the map_reduce command, and not
the instantiated collection that’s returned by default. Note if a
collection name isn’t returned in the map-reduce output (as, for
example, when using :out => => 1), then you must specify
this option or an ArgumentError will be raised.

See Also:

Core docs:

# File 'lib/mongo/collection.rb', line 542defmap_reduce(map,reduce,opts={})map=BSON::Code.new(map)unlessmap.is_a?(BSON::Code)reduce=BSON::Code.new(reduce)unlessreduce.is_a?(BSON::Code)raw=opts.delete(:raw)hash=BSON::OrderedHash.newhash['mapreduce']=self.namehash['map']=maphash['reduce']=reducehash.merge!optsresult=@db.command(hash)unlessMongo::Support.ok?(result)raiseMongo::OperationFailure,"map-reduce failed: #{result['errmsg']}"endifrawresultelsifresult["result"]@db[result["result"]]elseraiseArgumentError,"Could not instantiate collection from result. If you specified "+"{:out => {:inline => true}}, then you must also specify :raw => true to get the results."endend

Options Hash (opts):

run the operation in safe mode, which will run a getlasterror command on
the database to report any assertion. In addition, a hash can be provided
to run an fsync and/or wait for replication of the remove (>= 1.5.1).
Safe options provided here will override any safe options set on this
collection, its database, or the current connection. See the options for
DB#get_last_error for more details.

Raises:

# File 'lib/mongo/collection.rb', line 723defrename(new_name)casenew_namewhenSymbol,StringelseraiseTypeError,"new_name must be a string or symbol"endnew_name=new_name.to_sifnew_name.empty?ornew_name.include?".."raiseMongo::InvalidNSName,"collection names cannot be empty"endifnew_name.include?"$"raiseMongo::InvalidNSName,"collection names must not contain '$'"endifnew_name.match(/^\./)ornew_name.match(/\.$/)raiseMongo::InvalidNSName,"collection names must not start or end with '.'"end@db.rename_collection(@name,new_name)@name=new_nameend

- (ObjectId) save(doc, opts = {})

Save a document to this collection.

Parameters:

the document to be saved. If the document already has an ‘_id’
key, then an update (upsert) operation will be performed, and any existing
document with that _id is overwritten. Otherwise an insert operation is
performed.

Options Hash (opts):

run the operation in safe mode, which run a getlasterror command on the
database to report any assertion. In addition, a hash can be provided to
run an fsync and/or wait for replication of the save (>= 1.5.1). See the
options for DB#error.

Parameters:

a hash specifying elements which must be present for a document to be
updated. Note: the update command currently updates only the first document
matching the given selector. If you want all matching documents to be
updated, be sure to specify :multi => true.

Options Hash (opts):

update all documents matching the selector, as opposed to just the first
matching document. Note: only works in MongoDB 1.1.3 or later.

(Boolean):safe
— default:
+false+
—

If true, check that the save succeeded. OperationFailure will be raised on
an error. Note that a safe check requires an extra round-trip to the
database. Safe options provided here will override any safe options set on
this collection, its database object, or the current collection. See the
options for DB#get_last_error for details.