Class: Mongo::Collection
Overview
A named collection of documents in a database.
Instance Attribute Summary collapse
-
#db ⇒ Object
readonly
Returns the value of attribute db.
-
#hint ⇒ Object
Returns the value of attribute hint.
-
#name ⇒ Object
readonly
Returns the value of attribute name.
-
#pk_factory ⇒ Object
readonly
Returns the value of attribute pk_factory.
-
#safe ⇒ Object
readonly
Returns the value of attribute safe.
Instance Method Summary collapse
-
#[](name) ⇒ Collection
Return a sub-collection of this collection by name.
-
#count ⇒ Integer
(also: #size)
Get the number of documents in this collection.
-
#create_index(spec, opts = {}) ⇒ String
Create a new index.
-
#distinct(key, query = nil) ⇒ Array
Return a list of distinct values for
key
across all documents in the collection. -
#drop ⇒ Object
Drop the entire collection.
-
#drop_index(name) ⇒ Object
Drop a specified index.
-
#drop_indexes ⇒ Object
Drop all indexes.
-
#ensure_index(spec, opts = {}) ⇒ String
Calls create_index and sets a flag to not do so again for another X minutes.
-
#find(selector = {}, opts = {}) ⇒ Object
Query the database.
-
#find_and_modify(opts = {}) ⇒ Hash
Atomically update and return a document using MongoDB’s findAndModify command.
-
#find_one(spec_or_object_id = nil, opts = {}) ⇒ OrderedHash, Nil
Return a single object from the database.
-
#group(opts, condition = {}, initial = {}, reduce = nil, finalize = nil) ⇒ Array
Perform a group aggregation.
-
#index_information ⇒ Hash
Get information on the indexes for this collection.
-
#initialize(name, db, opts = {}) ⇒ Collection
constructor
Initialize a collection object.
-
#insert(doc_or_docs, opts = {}) ⇒ ObjectId, Array
(also: #<<)
Insert one or more documents into the collection.
-
#map_reduce(map, reduce, opts = {}) ⇒ Collection, Hash
(also: #mapreduce)
Perform a map-reduce operation on the current collection.
-
#options ⇒ Hash
Return a hash containing options that apply to this collection.
-
#remove(selector = {}, opts = {}) ⇒ Hash, true
Remove all documents from this collection.
-
#rename(new_name) ⇒ String
Rename this collection.
-
#save(doc, opts = {}) ⇒ ObjectId
Save a document to this collection.
-
#stats ⇒ Hash
Return stats on the collection.
-
#update(selector, document, opts = {}) ⇒ Hash, true
Update one or more documents in this collection.
Constructor Details
#initialize(name, db, opts = {}) ⇒ Collection
Initialize a collection object.
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
#db ⇒ Object (readonly)
Returns the value of attribute db.
23 24 25 |
# File 'lib/mongo/collection.rb', line 23 def db @db end |
#hint ⇒ Object
Returns the value of attribute hint.
23 24 25 |
# File 'lib/mongo/collection.rb', line 23 def hint @hint end |
#name ⇒ Object (readonly)
Returns the value of attribute name.
23 24 25 |
# File 'lib/mongo/collection.rb', line 23 def name @name end |
#pk_factory ⇒ Object (readonly)
Returns the value of attribute pk_factory.
23 24 25 |
# File 'lib/mongo/collection.rb', line 23 def pk_factory @pk_factory end |
#safe ⇒ Object (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.
102 103 104 105 106 |
# 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) raise "Collection #{name} doesn't exist. Currently in strict mode." end |
#count ⇒ Integer Also known as: size
Get the number of documents in this collection.
773 774 775 |
# File 'lib/mongo/collection.rb', line 773 def count find().count() end |
#create_index(spec, opts = {}) ⇒ String
Create a new index.
422 423 424 425 426 427 428 429 430 |
# File 'lib/mongo/collection.rb', line 422 def create_index(spec, opts={}) opts[:dropDups] = opts.delete(:drop_dups) if opts[:drop_dups] field_spec = parse_index_spec(spec) 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.
703 704 705 706 707 708 709 710 711 |
# File 'lib/mongo/collection.rb', line 703 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 |
#drop ⇒ Object
Drop the entire collection. USE WITH CAUTION.
485 486 487 |
# File 'lib/mongo/collection.rb', line 485 def drop @db.drop_collection(@name) end |
#drop_index(name) ⇒ Object
Drop a specified index.
469 470 471 472 |
# File 'lib/mongo/collection.rb', line 469 def drop_index(name) @cache[name.to_s] = nil @db.drop_index(@name, name) end |
#drop_indexes ⇒ Object
Drop all indexes.
477 478 479 480 481 482 |
# File 'lib/mongo/collection.rb', line 477 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.
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 |
# File 'lib/mongo/collection.rb', line 448 def ensure_index(spec, opts={}) now = Time.now.utc.to_i field_spec = parse_index_spec(spec) name = opts.delete(: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.
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 |
# File 'lib/mongo/collection.rb', line 168 def find(selector={}, opts={}) 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 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) 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)
503 504 505 506 507 508 509 510 |
# File 'lib/mongo/collection.rb', line 503 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.
218 219 220 221 222 223 224 225 226 227 228 229 230 |
# File 'lib/mongo/collection.rb', line 218 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.
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 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 |
# File 'lib/mongo/collection.rb', line 585 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_information ⇒ Hash
Get information on the indexes for this collection.
751 752 753 |
# File 'lib/mongo/collection.rb', line 751 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.
279 280 281 282 283 284 285 |
# File 'lib/mongo/collection.rb', line 279 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.
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 |
# File 'lib/mongo/collection.rb', line 542 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.delete(: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 |
#options ⇒ Hash
Return a hash containing options that apply to this collection. For all possible keys and values, see DB#create_collection.
759 760 761 |
# File 'lib/mongo/collection.rb', line 759 def @db.collections_info(@name).next_document['options'] end |
#remove(selector = {}, opts = {}) ⇒ Hash, true
Remove all documents from this collection.
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 |
# File 'lib/mongo/collection.rb', line 316 def remove(selector={}, opts={}) # Initial byte is 0. safe = opts.fetch(:safe, @safe) = BSON::ByteBuffer.new("\0\0\0\0") BSON::BSON_RUBY.serialize_cstr(, "#{@db.name}.#{@name}") .put_int(0) .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.(Mongo::Constants::OP_DELETE, , @db.name, nil, safe) else @connection.(Mongo::Constants::OP_DELETE, ) 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.
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 |
# File 'lib/mongo/collection.rb', line 723 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.
250 251 252 253 254 255 256 257 258 |
# File 'lib/mongo/collection.rb', line 250 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 |
#stats ⇒ Hash
Return stats on the collection. Uses MongoDB’s collstats command.
766 767 768 |
# File 'lib/mongo/collection.rb', line 766 def stats @db.command({:collstats => @name}) end |
#update(selector, document, opts = {}) ⇒ Hash, true
Update one or more documents in this collection.
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 |
# File 'lib/mongo/collection.rb', line 359 def update(selector, document, opts={}) # Initial byte is 0. safe = opts.fetch(:safe, @safe) = BSON::ByteBuffer.new("\0\0\0\0") BSON::BSON_RUBY.serialize_cstr(, "#{@db.name}.#{@name}") = 0 += 1 if opts[:upsert] += 2 if opts[:multi] .put_int() .put_binary(BSON::BSON_CODER.serialize(selector, false, true).to_s) .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.(Mongo::Constants::OP_UPDATE, , @db.name, nil, safe) else @connection.(Mongo::Constants::OP_UPDATE, , nil) end end end |