Class: Mongo::Collection
- Inherits:
-
Object
- Object
- Mongo::Collection
- Includes:
- Logging
- Defined in:
- lib/mongo/collection.rb
Overview
A named collection of documents in a database.
Instance Attribute Summary (collapse)
-
- (Object) db
readonly
Returns the value of attribute db.
-
- (Object) hint
Returns the value of attribute hint.
-
- (Object) name
readonly
Returns the value of attribute name.
-
- (Object) pk_factory
readonly
Returns the value of attribute pk_factory.
-
- (Object) safe
readonly
Returns the value of attribute safe.
Instance Method Summary (collapse)
-
- (Collection) [](name)
Return a sub-collection of this collection by name.
-
- (Boolean) capped?
Indicate whether this is a capped collection.
-
- (Integer) count(opts = {})
(also: #size)
Get the number of documents in this collection.
-
- (String) create_index(spec, opts = {})
Create a new index.
-
- (Array) distinct(key, query = nil)
Return a list of distinct values for key across all documents in the collection.
-
- (Object) drop
Drop the entire collection.
-
- (Object) drop_index(name)
Drop a specified index.
-
- (Object) drop_indexes
Drop all indexes.
-
- (String) ensure_index(spec, opts = {})
Calls create_index and sets a flag to not do so again for another X minutes.
-
- (Object) find(selector = {}, opts = {})
Query the database.
-
- (Hash) find_and_modify(opts = {})
Atomically update and return a document using MongoDB's findAndModify command.
-
- (OrderedHash, Nil) find_one(spec_or_object_id = nil, opts = {})
Return a single object from the database.
-
- (Array) group(opts, condition = {}, initial = {}, reduce = nil, finalize = nil)
Perform a group aggregation.
-
- (Hash) index_information
Get information on the indexes for this collection.
-
- (Collection) initialize(name, db, opts = {})
constructor
Initialize a collection object.
-
- (ObjectId, ...) insert(doc_or_docs, opts = {})
(also: #<<)
Insert one or more documents into the collection.
-
- (Collection, Hash) map_reduce(map, reduce, opts = {})
(also: #mapreduce)
Perform a map-reduce operation on the current collection.
-
- (Hash) options
Return a hash containing options that apply to this collection.
-
- (Object) read_preference
The value of the read preference.
-
- (Hash, true) remove(selector = {}, opts = {})
Remove all documents from this collection.
-
- (String) rename(new_name)
Rename this collection.
-
- (ObjectId) save(doc, opts = {})
Save a document to this collection.
-
- (Hash) stats
Return stats on the collection.
-
- (Hash, true) update(selector, document, opts = {})
Update one or more documents in this collection.
Methods included from Logging
#instrument, #log, #write_logging_startup_message
Constructor Details
- (Collection) initialize(name, db, opts = {})
Initialize a collection object.
Core docs:
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 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
# File 'lib/mongo/collection.rb', line 53 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. This will be made permanent" + "in v2.0." 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 @logger = @connection.logger @cache_time = @db.cache_time @cache = Hash.new(0) unless pk_factory @safe = opts.fetch(:safe, @db.safe) if value = opts[:read] Mongo::Support.validate_read_preference(value) else value = @db.read_preference end @read_preference = value.is_a?(Hash) ? value.dup : value end @pk_factory = pk_factory || opts[:pk] || BSON::ObjectId @hint = nil end |
Instance Attribute Details
- (Object) db (readonly)
Returns the value of attribute db
24 25 26 |
# File 'lib/mongo/collection.rb', line 24 def db @db end |
- (Object) hint
Returns the value of attribute hint
24 25 26 |
# File 'lib/mongo/collection.rb', line 24 def hint @hint end |
- (Object) name (readonly)
Returns the value of attribute name
24 25 26 |
# File 'lib/mongo/collection.rb', line 24 def name @name end |
- (Object) pk_factory (readonly)
Returns the value of attribute pk_factory
24 25 26 |
# File 'lib/mongo/collection.rb', line 24 def pk_factory @pk_factory end |
- (Object) safe (readonly)
Returns the value of attribute safe
24 25 26 |
# File 'lib/mongo/collection.rb', line 24 def safe @safe end |
Instance Method Details
- (Collection) [](name)
Return a sub-collection of this collection by name. If 'users' is a collection, then 'users.comments' is a sub-collection of users.
126 127 128 129 130 131 |
# File 'lib/mongo/collection.rb', line 126 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 |
- (Boolean) capped?
Indicate whether this is a capped collection.
111 112 113 |
# File 'lib/mongo/collection.rb', line 111 def capped? @db.command({:collstats => @name})['capped'] == 1 end |
- (Integer) count(opts = {}) Also known as: size
Get the number of documents in this collection.
865 866 867 868 869 |
# File 'lib/mongo/collection.rb', line 865 def count(opts={}) find(opts[:query], :skip => opts[:skip], :limit => opts[:limit]).count(true) end |
- (String) create_index(spec, opts = {})
Create a new index.
Core docs:
490 491 492 493 494 495 496 497 498 499 |
# File 'lib/mongo/collection.rb', line 490 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 |
- (Array) distinct(key, query = nil)
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.
791 792 793 794 795 796 797 798 799 |
# File 'lib/mongo/collection.rb', line 791 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 |
- (Object) drop
Drop the entire collection. USE WITH CAUTION.
558 559 560 |
# File 'lib/mongo/collection.rb', line 558 def drop @db.drop_collection(@name) end |
- (Object) drop_index(name)
Drop a specified index.
Core docs:
539 540 541 542 543 544 545 |
# File 'lib/mongo/collection.rb', line 539 def drop_index(name) if name.is_a?(Array) return drop_index(index_name(name)) end @cache[name.to_s] = nil @db.drop_index(@name, name) end |
- (Object) drop_indexes
Drop all indexes.
Core docs:
550 551 552 553 554 555 |
# File 'lib/mongo/collection.rb', line 550 def drop_indexes @cache = {} # Note: calling drop_indexes with no args will drop them all. @db.drop_index(@name, '*') end |
- (String) ensure_index(spec, opts = {})
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.
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 |
# File 'lib/mongo/collection.rb', line 517 def ensure_index(spec, opts={}) now = Time.now.utc.to_i opts[:dropDups] = opts[:drop_dups] if opts[:drop_dups] 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 |
- (Object) find(selector = {}, opts = {})
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.
Core docs:
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 |
# File 'lib/mongo/collection.rb', line 207 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 max_scan = opts.delete(:max_scan) return_key = opts.delete(:return_key) transformer = opts.delete(:transformer) show_disk_loc = opts.delete(:show_disk_loc) read = opts.delete(:read) || @read_preference 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, :max_scan => max_scan, :show_disk_loc => show_disk_loc, :return_key => return_key, :read => read }) if block_given? yield cursor cursor.close nil else cursor end end |
- (Hash) find_and_modify(opts = {})
Atomically update and return a document using MongoDB's findAndModify command. (MongoDB > 1.3.0)
Core docs:
576 577 578 579 580 581 582 583 |
# File 'lib/mongo/collection.rb', line 576 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 |
- (OrderedHash, Nil) find_one(spec_or_object_id = nil, opts = {})
Return a single object from the database.
277 278 279 280 281 282 283 284 285 286 287 288 289 |
# File 'lib/mongo/collection.rb', line 277 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 |
- (Array) group(opts, condition = {}, initial = {}, reduce = nil, finalize = nil)
Perform a group aggregation.
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 |
# File 'lib/mongo/collection.rb', line 666 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 and will be remove in v2.0." + "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 |
- (Hash) index_information
Get information on the indexes for this collection.
Core docs:
839 840 841 |
# File 'lib/mongo/collection.rb', line 839 def index_information @db.index_information(@name) end |
- (ObjectId, ...) insert(doc_or_docs, opts = {}) Also known as: <<
Insert one or more documents into the collection.
Core docs:
349 350 351 352 353 354 355 |
# File 'lib/mongo/collection.rb', line 349 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, opts) result.size > 1 ? result : result.first end |
- (Collection, Hash) map_reduce(map, reduce, opts = {}) Also known as: mapreduce
Perform a map-reduce operation on the current collection.
Core docs:
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 |
# File 'lib/mongo/collection.rb', line 615 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 if hash[:sort] hash[:sort] = Mongo::Support.format_order_clause(hash[:sort]) end result = @db.command(hash) unless Mongo::Support.ok?(result) raise Mongo::OperationFailure, "map-reduce failed: #{result['errmsg']}" end if raw result elsif result["result"] if result['result'].is_a? BSON::OrderedHash and result['result'].has_key? 'db' and result['result'].has_key? 'collection' otherdb = @db.connection[result['result']['db']] otherdb[result['result']['collection']] else @db[result["result"]] end 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 |
- (Hash) options
Return a hash containing options that apply to this collection. For all possible keys and values, see DB#create_collection.
847 848 849 |
# File 'lib/mongo/collection.rb', line 847 def @db.collections_info(@name).next_document['options'] end |
- (Object) read_preference
The value of the read preference. This will be either :primary, :secondary, or an object representing the tags to be read from.
720 721 722 |
# File 'lib/mongo/collection.rb', line 720 def read_preference @read_preference end |
- (Hash, true) remove(selector = {}, opts = {})
Remove all documents from this collection.
Core docs:
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 |
# File 'lib/mongo/collection.rb', line 384 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, @connection.max_bson_size).to_s) 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 |
- (String) rename(new_name)
Rename this collection.
Note: If operating in auth mode, the client must be authorized as an admin to perform this operation.
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 |
# File 'lib/mongo/collection.rb', line 811 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 |
- (ObjectId) save(doc, opts = {})
Save a document to this collection.
307 308 309 310 311 312 313 314 315 |
# File 'lib/mongo/collection.rb', line 307 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 |
- (Hash) stats
Return stats on the collection. Uses MongoDB's collstats command.
854 855 856 |
# File 'lib/mongo/collection.rb', line 854 def stats @db.command({:collstats => @name}) end |
- (Hash, true) update(selector, document, opts = {})
Update one or more documents in this collection.
Core docs:
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 |
# File 'lib/mongo/collection.rb', line 427 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, @connection.max_bson_size).to_s) 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, ) end end end |