Class: Mongo::Collection

Inherits:
Object show all
Defined in:
lib/mongo/collection.rb

Overview

A named collection of documents in a database.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, db, opts = {}) ⇒ Collection

Initialize a collection object.

Parameters:

  • name (String, Symbol)

    the name of the collection.

  • db (DB)

    a MongoDB database instance.

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :pk (:create_pk) — default: BSON::ObjectId

    A primary key factory to use other than the default BSON::ObjectId.

  • :safe (Boolean, Hash) — default: false

    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.

Raises:

  • (InvalidNSName)

    if collection name is empty, contains ‘$’, or starts or ends with ‘.’

  • (TypeError)

    if collection name is not a string or symbol



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/mongo/collection.rb', line 47

def initialize(name, db, opts={})
  if db.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, db
  end

  case name
  when Symbol, String
  else
    raise TypeError, "new_name must be a string or symbol"
  end

  name = name.to_s

  if name.empty? or name.include? ".."
    raise Mongo::InvalidNSName, "collection names cannot be empty"
  end
  if name.include? "$"
    raise Mongo::InvalidNSName, "collection names must not contain '$'" unless name =~ /((^\$cmd)|(oplog\.\$main))/
  end
  if name.match(/^\./) or name.match(/\.$/)
    raise Mongo::InvalidNSName, "collection names must not start or end with '.'"
  end

  if opts.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 = opts
  else
    pk_factory = nil
  end

  @db, @name  = db, name
  @connection = @db.connection
  @cache_time = @db.cache_time
  @cache = Hash.new(0)
  unless pk_factory
    @safe = opts.fetch(:safe, @db.safe)
  end
  @pk_factory = pk_factory || opts[:pk] || BSON::ObjectId
  @hint = nil
end

Instance Attribute Details

#dbObject (readonly)

Returns the value of attribute db.



23
24
25
# File 'lib/mongo/collection.rb', line 23

def db
  @db
end

#hintObject

Returns the value of attribute hint.



23
24
25
# File 'lib/mongo/collection.rb', line 23

def hint
  @hint
end

#nameObject (readonly)

Returns the value of attribute name.



23
24
25
# File 'lib/mongo/collection.rb', line 23

def name
  @name
end

#pk_factoryObject (readonly)

Returns the value of attribute pk_factory.



23
24
25
# File 'lib/mongo/collection.rb', line 23

def pk_factory
  @pk_factory
end

#safeObject (readonly)

Returns the value of attribute safe.



23
24
25
# File 'lib/mongo/collection.rb', line 23

def safe
  @safe
end

Instance Method Details

#[](name) ⇒ Collection

Return a sub-collection of this collection by name. If ‘users’ is a collection, then ‘users.comments’ is a sub-collection of users.

Parameters:

  • name (String, Symbol)

    the collection to return

Returns:

Raises:



102
103
104
105
106
107
# File 'lib/mongo/collection.rb', line 102

def [](name)
  name = "#{self.name}.#{name}"
  return Collection.new(name, db) if !db.strict? ||
    db.collection_names.include?(name.to_s)
  raise "Collection #{name} doesn't exist. Currently in strict mode."
end

#countInteger Also known as: size

Get the number of documents in this collection.

Returns:

  • (Integer)


796
797
798
# File 'lib/mongo/collection.rb', line 796

def count
  find().count()
end

#create_index(spec, opts = {}) ⇒ String

Create a new index.

Examples:

Creating a compound index:

@posts.create_index([['subject', Mongo::ASCENDING], ['created_at', Mongo::DESCENDING]])

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}}

A geospatial index with alternate longitude and latitude:

@restaurants.create_index([['location', Mongo::GEO2D]], :min => 500, :max => 500)

Parameters:

  • spec (String, Array)

    should be either a single field name or an array of

    field name, direction

    pairs. Directions should be specified

    as Mongo::ASCENDING, Mongo::DESCENDING, or Mongo::GEO2D.

    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.

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :unique (Boolean) — default: false

    if true, this index will enforce a uniqueness constraint.

  • :background (Boolean) — default: false

    indicate that the index should be built in the background. This feature is only available in MongoDB >= 1.3.2.

  • :drop_dups (Boolean) — default: nil

    If creating a unique index on a collection with pre-existing records, this option will keep the first document the database indexes and drop all subsequent with duplicate values.

  • :min (Integer) — default: nil

    specify the minimum longitude and latitude for a geo index.

  • :max (Integer) — default: nil

    specify the maximum longitude and latitude for a geo index.

Returns:

  • (String)

    the name of the index created.



444
445
446
447
448
449
450
451
452
453
# File 'lib/mongo/collection.rb', line 444

def create_index(spec, opts={})
  opts[:dropDups] = opts[:drop_dups] if opts[:drop_dups]
  field_spec = parse_index_spec(spec)
  opts = opts.dup
  name = opts.delete(:name) || generate_index_name(field_spec)
  name = name.to_s if name

  generate_indexes(field_spec, name, opts)
  name
end

#distinct(key, query = nil) ⇒ Array

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]

Parameters:

  • key (String, Symbol, OrderedHash)

    or hash to group by.

  • query (Hash) (defaults to: nil)

    a selector for limiting the result set over which to group.

Returns:

  • (Array)

    an array of distinct values.

Raises:



726
727
728
729
730
731
732
733
734
# File 'lib/mongo/collection.rb', line 726

def distinct(key, query=nil)
  raise MongoArgumentError unless [String, Symbol].include?(key.class)
  command = BSON::OrderedHash.new
  command[:distinct] = @name
  command[:key]      = key.to_s
  command[:query]    = query

  @db.command(command)["values"]
end

#dropObject

Drop the entire collection. USE WITH CAUTION.



508
509
510
# File 'lib/mongo/collection.rb', line 508

def drop
  @db.drop_collection(@name)
end

#drop_index(name) ⇒ Object

Drop a specified index.

Parameters:



492
493
494
495
# File 'lib/mongo/collection.rb', line 492

def drop_index(name)
  @cache[name.to_s] = nil
  @db.drop_index(@name, name)
end

#drop_indexesObject

Drop all indexes.



500
501
502
503
504
505
# File 'lib/mongo/collection.rb', line 500

def drop_indexes
  @cache = {}

  # Note: calling drop_indexes with no args will drop them all.
  @db.drop_index(@name, '*')
end

#ensure_index(spec, opts = {}) ⇒ String

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 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.

Examples:

Call sequence:

Time t: @posts.ensure_index([['subject', Mongo::ASCENDING])  -- calls create_index and
  sets the 5 minute cache
Time t+2min : @posts.ensure_index([['subject', Mongo::ASCENDING])  -- doesn't do anything
Time t+3min : @posts.ensure_index([['something_else', Mongo::ASCENDING])  -- calls create_index
  and sets 5 minute cache
Time t+10min : @posts.ensure_index([['subject', Mongo::ASCENDING])  -- calls create_index and
  resets the 5 minute counter

Returns:

  • (String)

    the name of the index.



471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# File 'lib/mongo/collection.rb', line 471

def ensure_index(spec, opts={})
  now = Time.now.utc.to_i
  field_spec = parse_index_spec(spec)

  name = opts[:name] || generate_index_name(field_spec)
  name = name.to_s if name

  if !@cache[name] || @cache[name] <= now
    generate_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_time
  name
end

#find(selector = {}, opts = {}) ⇒ Object

Query the database.

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:

  • selector (Hash) (defaults to: {})

    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).

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :fields (Array, Hash)

    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.

  • :skip (Integer)

    number of documents to skip from the beginning of the result set

  • :limit (Integer)

    maximum number of documents to return

  • :sort (Array)

    an array of [key, direction] pairs to sort by. Direction should be specified as Mongo::ASCENDING (or :ascending / :asc) or Mongo::DESCENDING (or :descending / :desc)

  • :hint (String, Array, OrderedHash)

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

  • :snapshot (Boolean) — 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 www.mongodb.org/display/DOCS/How+to+do+Snapshotting+in+the+Mongo+Database

  • :batch_size (Boolean) — 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.

  • :timeout (Boolean) — 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.

  • :max_scan (Integer) — default: nil

    Limit the number of items to scan on both collection scans and indexed queries..

  • :show_disk_loc (Boolean) — default: false

    Return the disk location of each query result (for debugging).

  • :return_key (Boolean) — default: false

    Return the index key used to obtain the result (for debugging).

  • :transformer (Block) — default: nil

    a block for tranforming returned documents. This is normally used by object mappers to convert each returned document to an instance of a class.

Raises:

  • (ArgumentError)

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

  • (RuntimeError)

    if given unknown options



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/mongo/collection.rb', line 178

def find(selector={}, opts={})
  opts   = opts.dup
  fields = opts.delete(:fields)
  fields = ["_id"] if fields && fields.empty?
  skip   = opts.delete(:skip) || skip || 0
  limit  = opts.delete(:limit) || 0
  sort   = opts.delete(:sort)
  hint   = opts.delete(:hint)
  snapshot   = opts.delete(:snapshot)
  batch_size = opts.delete(:batch_size)
  timeout    = (opts.delete(:timeout) == false) ? false : true
  transformer = opts.delete(:transformer)

  if timeout == false && !block_given?
    raise ArgumentError, "Collection#find must be invoked with a block when timeout is disabled."
  end

  if hint
    hint = normalize_hint_fields(hint)
  else
    hint = @hint        # assumed to be normalized already
  end

  raise RuntimeError, "Unknown options [#{opts.inspect}]" unless opts.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,
    :transformer => transformer,
  })

  if block_given?
    yield cursor
    cursor.close
    nil
  else
    cursor
  end
end

#find_and_modify(opts = {}) ⇒ Hash

Atomically update and return a document using MongoDB’s findAndModify command. (MongoDB > 1.3.0)

Parameters:

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :query (Hash) — default: {}

    a query selector document for matching the desired document.

  • :update (Hash) — default: nil

    the update operation to perform on the matched document.

  • :sort (Array, String, OrderedHash) — default: {}

    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.

  • :remove (Boolean) — default: false

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

  • :new (Boolean) — default: false

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

Returns:

  • (Hash)

    the matched document.



526
527
528
529
530
531
532
533
# File 'lib/mongo/collection.rb', line 526

def find_and_modify(opts={})
  cmd = BSON::OrderedHash.new
  cmd[:findandmodify] = @name
  cmd.merge!(opts)
  cmd[:sort] = Mongo::Support.format_order_clause(opts[:sort]) if opts[:sort]

  @db.command(cmd)['value']
end

#find_one(spec_or_object_id = nil, opts = {}) ⇒ OrderedHash, Nil

Return a single object from the database.

Parameters:

  • spec_or_object_id (Hash, ObjectId, Nil) (defaults to: nil)

    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.

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • any (Hash)

    valid options that can be send to Collection#find

Returns:

  • (OrderedHash, Nil)

    a single document or nil if no result is found.

Raises:

  • (TypeError)

    if the argument is of an improper type.



240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/mongo/collection.rb', line 240

def find_one(spec_or_object_id=nil, opts={})
  spec = case spec_or_object_id
         when nil
           {}
         when BSON::ObjectId
           {:_id => spec_or_object_id}
         when Hash
           spec_or_object_id
         else
           raise TypeError, "spec_or_object_id must be an instance of ObjectId or Hash, or nil"
         end
  find(spec, opts.merge(:limit => -1)).next_document
end

#group(opts, condition = {}, initial = {}, reduce = nil, finalize = nil) ⇒ Array

Perform a group aggregation.

Parameters:

  • opts (Hash)

    the options for this group operation. The minimum required are :initial and :reduce.

Options Hash (opts):

  • :key (Array, String, Symbol) — default: nil

    Either the name of a field or a list of fields to group by (optional).

  • :keyf (String, BSON::Code) — default: nil

    A JavaScript function to be used to generate the grouping keys (optional).

  • :cond (String, BSON::Code) — default: {}

    A document specifying a query for filtering the documents over which the aggregation is run (optional).

  • :initial (Hash)

    the initial value of the aggregation counter object (required).

  • :reduce (String, BSON::Code) — default: nil

    a JavaScript aggregation function (required).

  • :finalize (String, BSON::Code) — default: nil

    a JavaScript function that receives and modifies each of the resultant grouped objects. Available only when group is run with command set to true.

Returns:

  • (Array)

    the command response consisting of grouped items.



608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
# File 'lib/mongo/collection.rb', line 608

def group(opts, condition={}, initial={}, reduce=nil, finalize=nil)
  if opts.is_a?(Hash)
    return new_group(opts)
  else
    warn "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"
  end

  reduce = BSON::Code.new(reduce) unless reduce.is_a?(BSON::Code)

  group_command = {
    "group" => {
      "ns"      => @name,
      "$reduce" => reduce,
      "cond"    => condition,
      "initial" => initial
    }
  }

  if opts.is_a?(Symbol)
    raise MongoArgumentError, "Group takes either an array of fields to group by or a JavaScript function" +
      "in the form of a String or BSON::Code."
  end

  unless opts.nil?
    if opts.is_a? Array
      key_type = "key"
      key_value = {}
      opts.each { |k| key_value[k] = 1 }
    else
      key_type  = "$keyf"
      key_value = opts.is_a?(BSON::Code) ? opts : BSON::Code.new(opts)
    end

    group_command["group"][key_type] = key_value
  end

  finalize = BSON::Code.new(finalize) if finalize.is_a?(String)
  if finalize.is_a?(BSON::Code)
    group_command['group']['finalize'] = finalize
  end

  result = @db.command(group_command)

  if Mongo::Support.ok?(result)
    result["retval"]
  else
    raise OperationFailure, "group command failed: #{result['errmsg']}"
  end
end

#index_informationHash

Get information on the indexes for this collection.

Returns:

  • (Hash)

    a hash where the keys are index names.



774
775
776
# File 'lib/mongo/collection.rb', line 774

def index_information
  @db.index_information(@name)
end

#insert(doc_or_docs, opts = {}) ⇒ ObjectId, Array Also known as: <<

Insert one or more documents into the collection.

Parameters:

  • doc_or_docs (Hash, Array)

    a document (as a hash) or array of documents to be inserted.

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :safe (Boolean, Hash) — default: +false+

    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.

See Also:

  • for options that can be passed to :safe.


301
302
303
304
305
306
307
# File 'lib/mongo/collection.rb', line 301

def insert(doc_or_docs, opts={})
  doc_or_docs = [doc_or_docs] unless doc_or_docs.is_a?(Array)
  doc_or_docs.collect! { |doc| @pk_factory.create_pk(doc) }
  safe = opts.fetch(:safe, @safe)
  result = insert_documents(doc_or_docs, @name, true, safe)
  result.size > 1 ? result : result.first
end

#map_reduce(map, reduce, opts = {}) ⇒ Collection, Hash Also known as: mapreduce

Perform a map-reduce operation on the current collection.

Parameters:

  • map (String, BSON::Code)

    a map function, written in JavaScript.

  • reduce (String, BSON::Code)

    a reduce function, written in JavaScript.

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :query (Hash) — default: {}

    a query selector document, like what’s passed to #find, to limit the operation to a subset of the collection.

  • :sort (Array) — default: []

    an array of [key, direction] pairs to sort by. Direction should be specified as Mongo::ASCENDING (or :ascending / :asc) or Mongo::DESCENDING (or :descending / :desc)

  • :limit (Integer) — default: nil

    if passing a query, number of objects to return from the collection.

  • :finalize (String, BSON::Code) — default: nil

    a javascript function to apply to the result set after the map/reduce operation has finished.

  • :out (String) — default: nil

    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.

  • :keeptemp (Boolean) — 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.

  • :verbose (Boolean) — default: false

    if true, provides statistics on job execution time.

  • :raw (Boolean) — 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.

Returns:

  • (Collection, Hash)

    a Mongo::Collection object or a Hash with the map-reduce command’s results.

Raises:

  • ArgumentError if you specify => {:inline => true} but don’t specify :raw => true.

See Also:



565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
# File 'lib/mongo/collection.rb', line 565

def map_reduce(map, reduce, opts={})
  map    = BSON::Code.new(map) unless map.is_a?(BSON::Code)
  reduce = BSON::Code.new(reduce) unless reduce.is_a?(BSON::Code)
  raw    = opts[:raw]

  hash = BSON::OrderedHash.new
  hash['mapreduce'] = self.name
  hash['map'] = map
  hash['reduce'] = reduce
  hash.merge! opts

  result = @db.command(hash)
  unless Mongo::Support.ok?(result)
    raise Mongo::OperationFailure, "map-reduce failed: #{result['errmsg']}"
  end

  if raw
    result
  elsif result["result"]
    @db[result["result"]]
  else
    raise ArgumentError, "Could not instantiate collection from result. If you specified " +
      "{:out => {:inline => true}}, then you must also specify :raw => true to get the results."
  end
end

#optionsHash

Return a hash containing options that apply to this collection. For all possible keys and values, see DB#create_collection.

Returns:

  • (Hash)

    options that apply to this collection.



782
783
784
# File 'lib/mongo/collection.rb', line 782

def options
  @db.collections_info(@name).next_document['options']
end

#remove(selector = {}, opts = {}) ⇒ Hash, true

Remove all documents from this collection.

Examples:

remove all documents from the ‘users’ collection:

users.remove
users.remove({})

remove only documents that have expired:

users.remove({:expire => {"$lte" => Time.now}})

Parameters:

  • selector (Hash) (defaults to: {})

    If specified, only matching documents will be removed.

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :safe (Boolean, Hash) — default: +false+

    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.

Returns:

  • (Hash, true)

    Returns a Hash containing the last error object if running in safe mode. Otherwise, returns true.

Raises:

See Also:

  • for options that can be passed to :safe.


338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/mongo/collection.rb', line 338

def remove(selector={}, opts={})
  # Initial byte is 0.
  safe = opts.fetch(:safe, @safe)
  message = BSON::ByteBuffer.new("\0\0\0\0")
  BSON::BSON_RUBY.serialize_cstr(message, "#{@db.name}.#{@name}")
  message.put_int(0)
  message.put_binary(BSON::BSON_CODER.serialize(selector, false, true).to_s)

  @connection.instrument(:remove, :database => @db.name, :collection => @name, :selector => selector) do
    if safe
      @connection.send_message_with_safe_check(Mongo::Constants::OP_DELETE, message, @db.name, nil, safe)
    else
      @connection.send_message(Mongo::Constants::OP_DELETE, message)
      true
    end
  end
end

#rename(new_name) ⇒ String

Rename this collection.

Note: If operating in auth mode, the client must be authorized as an admin to perform this operation.

Parameters:

  • new_name (String)

    the new name for this collection

Returns:

  • (String)

    the name of the new collection.

Raises:



746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
# File 'lib/mongo/collection.rb', line 746

def rename(new_name)
  case new_name
  when Symbol, String
  else
    raise TypeError, "new_name must be a string or symbol"
  end

  new_name = new_name.to_s

  if new_name.empty? or new_name.include? ".."
    raise Mongo::InvalidNSName, "collection names cannot be empty"
  end
  if new_name.include? "$"
    raise Mongo::InvalidNSName, "collection names must not contain '$'"
  end
  if new_name.match(/^\./) or new_name.match(/\.$/)
    raise Mongo::InvalidNSName, "collection names must not start or end with '.'"
  end

  @db.rename_collection(@name, new_name)
  @name = new_name
end

#save(doc, opts = {}) ⇒ ObjectId

Save a document to this collection.

Parameters:

  • doc (Hash)

    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.

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :safe (Boolean, Hash) — default: +false+

    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.

Returns:

  • (ObjectId)

    the _id of the saved document.

Raises:

See Also:

  • for options that can be passed to :safe.


272
273
274
275
276
277
278
279
280
# File 'lib/mongo/collection.rb', line 272

def save(doc, opts={})
  if doc.has_key?(:_id) || doc.has_key?('_id')
    id = doc[:_id] || doc['_id']
    update({:_id => id}, doc, :upsert => true, :safe => opts.fetch(:safe, @safe))
    id
  else
    insert(doc, :safe => opts.fetch(:safe, @safe))
  end
end

#statsHash

Return stats on the collection. Uses MongoDB’s collstats command.

Returns:



789
790
791
# File 'lib/mongo/collection.rb', line 789

def stats
  @db.command({:collstats => @name})
end

#update(selector, document, opts = {}) ⇒ Hash, true

Update one or more documents in this collection.

Parameters:

  • selector (Hash)

    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.

  • document (Hash)

    a hash specifying the fields to be changed in the selected document, or (in the case of an upsert) the document to be inserted

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :upsert (Boolean) — default: +false+

    if true, performs an upsert (update or insert)

  • :multi (Boolean) — default: +false+

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

  • :safe (Boolean) — 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.

Returns:

  • (Hash, true)

    Returns a Hash containing the last error object if running in safe mode. Otherwise, returns true.



381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
# File 'lib/mongo/collection.rb', line 381

def update(selector, document, opts={})
  # Initial byte is 0.
  safe = opts.fetch(:safe, @safe)
  message = BSON::ByteBuffer.new("\0\0\0\0")
  BSON::BSON_RUBY.serialize_cstr(message, "#{@db.name}.#{@name}")
  update_options  = 0
  update_options += 1 if opts[:upsert]
  update_options += 2 if opts[:multi]
  message.put_int(update_options)
  message.put_binary(BSON::BSON_CODER.serialize(selector, false, true).to_s)
  message.put_binary(BSON::BSON_CODER.serialize(document, false, true).to_s)

  @connection.instrument(:update, :database => @db.name, :collection => @name, :selector => selector, :document => document) do
    if safe
      @connection.send_message_with_safe_check(Mongo::Constants::OP_UPDATE, message, @db.name, nil, safe)
    else
      @connection.send_message(Mongo::Constants::OP_UPDATE, message)
    end
  end
end