Class: Mongo::Collection
- Includes:
- Logging, WriteConcern
- Defined in:
- lib/mongo/collection.rb
Overview
A named collection of documents in a database.
Instance Attribute Summary collapse
-
#acceptable_latency ⇒ Object
Read Preference.
-
#capped ⇒ Object
readonly
Returns the value of attribute capped.
-
#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.
-
#read ⇒ Object
Read Preference.
-
#tag_sets ⇒ Object
Read Preference.
-
#write_concern ⇒ Object
readonly
Returns the value of attribute write_concern.
Attributes included from WriteConcern
Instance Method Summary collapse
-
#[](name) ⇒ Collection
Return a sub-collection of this collection by name.
-
#aggregate(pipeline = nil, opts = {}) ⇒ Array
Perform an aggregation using the aggregation framework on the current collection.
-
#capped? ⇒ Boolean
Indicate whether this is a capped collection.
-
#count(opts = {}) ⇒ Integer
(also: #size)
Get the number of documents in this collection.
-
#create_index(spec, opts = {}) ⇒ String
Create a new index.
-
#distinct(key, query = nil, opts = {}) ⇒ Array
Return a list of distinct values for
keyacross 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, ...
(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.
-
#named_hint=(hint = nil) ⇒ Object
Set a hint field using a named index.
-
#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.
Methods included from WriteConcern
#get_write_concern, gle?, #write_concern_from_legacy
Methods included from Logging
#instrument, instrumenter, instrumenter=, #log, #write_logging_startup_message
Constructor Details
#initialize(name, db, opts = {}) ⇒ Collection
Initialize a collection object.
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 104 105 106 107 108 109 110 111 112 |
# File 'lib/mongo/collection.rb', line 67 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 raise TypeError, "Collection name must be a String or Symbol." unless [String, Symbol].include?(name.class) name = name.to_s raise Mongo::InvalidNSName, "Collection names cannot be empty." if name.empty? || name.include?("..") if name.include?("$") raise Mongo::InvalidNSName, "Collection names must not contain '$'" unless name =~ /((^\$cmd)|(oplog\.\$main))/ end raise Mongo::InvalidNSName, "Collection names must not start or end with '.'" if name.match(/^\./) || name.match(/\.$/) pk_factory = nil 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 end @db, @name = db, name @connection = @db.connection @logger = @connection.logger @cache_time = @db.cache_time @cache = Hash.new(0) unless pk_factory @write_concern = get_write_concern(opts, db) @read = opts[:read] || @db.read Mongo::ReadPreference::validate(@read) @capped = opts[:capped] @tag_sets = opts.fetch(:tag_sets, @db.tag_sets) @acceptable_latency = opts.fetch(:acceptable_latency, @db.acceptable_latency) end @pk_factory = pk_factory || opts[:pk] || BSON::ObjectId @hint = nil end |
Instance Attribute Details
#acceptable_latency ⇒ Object
Read Preference
30 31 32 |
# File 'lib/mongo/collection.rb', line 30 def acceptable_latency @acceptable_latency end |
#capped ⇒ Object (readonly)
Returns the value of attribute capped.
22 23 24 |
# File 'lib/mongo/collection.rb', line 22 def capped @capped end |
#db ⇒ Object (readonly)
Returns the value of attribute db.
22 23 24 |
# File 'lib/mongo/collection.rb', line 22 def db @db end |
#hint ⇒ Object
Returns the value of attribute hint.
22 23 24 |
# File 'lib/mongo/collection.rb', line 22 def hint @hint end |
#name ⇒ Object (readonly)
Returns the value of attribute name.
22 23 24 |
# File 'lib/mongo/collection.rb', line 22 def name @name end |
#pk_factory ⇒ Object (readonly)
Returns the value of attribute pk_factory.
22 23 24 |
# File 'lib/mongo/collection.rb', line 22 def pk_factory @pk_factory end |
#read ⇒ Object
Read Preference
30 31 32 |
# File 'lib/mongo/collection.rb', line 30 def read @read end |
#tag_sets ⇒ Object
Read Preference
30 31 32 |
# File 'lib/mongo/collection.rb', line 30 def tag_sets @tag_sets end |
#write_concern ⇒ Object (readonly)
Returns the value of attribute write_concern.
22 23 24 |
# File 'lib/mongo/collection.rb', line 22 def write_concern @write_concern 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.
135 136 137 138 139 140 |
# File 'lib/mongo/collection.rb', line 135 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 |
#aggregate(pipeline = nil, opts = {}) ⇒ Array
Aggregate requires server version >= 2.1.1
Field References: Within an expression, field names must be quoted and prefixed by a dollar sign ($).
Perform an aggregation using the aggregation framework on the current collection.
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 |
# File 'lib/mongo/collection.rb', line 684 def aggregate(pipeline=nil, opts={}) raise MongoArgumentError, "pipeline must be an array of operators" unless pipeline.class == Array raise MongoArgumentError, "pipeline operators must be hashes" unless pipeline.all? { |op| op.class == Hash } hash = BSON::OrderedHash.new hash['aggregate'] = self.name hash['pipeline'] = pipeline result = @db.command(hash, (opts)) unless Mongo::Support.ok?(result) raise Mongo::OperationFailure, "aggregate failed: #{result['errmsg']}" end return result["result"] end |
#capped? ⇒ Boolean
Indicate whether this is a capped collection.
120 121 122 |
# File 'lib/mongo/collection.rb', line 120 def capped? @capped ||= [1, true].include?(@db.command({:collstats => @name})['capped']) end |
#count(opts = {}) ⇒ Integer Also known as: size
Get the number of documents in this collection.
987 988 989 990 991 992 993 |
# File 'lib/mongo/collection.rb', line 987 def count(opts={}) find(opts[:query], :skip => opts[:skip], :limit => opts[:limit], :read => opts[:read], :comment => opts[:comment]).count(true) end |
#create_index(spec, opts = {}) ⇒ String
Create a new index.
545 546 547 548 549 550 551 552 553 554 |
# File 'lib/mongo/collection.rb', line 545 def create_index(spec, opts={}) opts[:dropDups] = opts[:drop_dups] if opts[:drop_dups] opts[:bucketSize] = opts[:bucket_size] if opts[:bucket_size] 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, opts = {}) ⇒ 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.
910 911 912 913 914 915 916 917 918 |
# File 'lib/mongo/collection.rb', line 910 def distinct(key, query=nil, opts={}) 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, (opts))["values"] end |
#drop ⇒ Object
Drop the entire collection. USE WITH CAUTION.
613 614 615 |
# File 'lib/mongo/collection.rb', line 613 def drop @db.drop_collection(@name) end |
#drop_index(name) ⇒ Object
Drop a specified index.
594 595 596 597 598 599 600 |
# File 'lib/mongo/collection.rb', line 594 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 |
#drop_indexes ⇒ Object
Drop all indexes.
605 606 607 608 609 610 |
# File 'lib/mongo/collection.rb', line 605 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 propagated 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.
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 |
# File 'lib/mongo/collection.rb', line 572 def ensure_index(spec, opts={}) now = Time.now.utc.to_i opts[:dropDups] = opts[:drop_dups] if opts[:drop_dups] opts[:bucketSize] = opts[:bucket_size] if opts[:bucket_size] 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.
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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 |
# File 'lib/mongo/collection.rb', line 226 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) named_hint = opts.delete(:named_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) comment = opts.delete(:comment) read = opts.delete(:read) || @read tag_sets = opts.delete(:tag_sets) || @tag_sets acceptable_latency = opts.delete(:acceptable_latency) || @acceptable_latency 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 || named_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, :tag_sets => tag_sets, :comment => comment, :acceptable_latency => acceptable_latency }) if block_given? begin yield cursor ensure cursor.close end 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)
638 639 640 641 642 643 644 645 646 647 648 649 |
# File 'lib/mongo/collection.rb', line 638 def find_and_modify(opts={}) full_response = opts.delete(:full_response) cmd = BSON::OrderedHash.new cmd[:findandmodify] = @name cmd.merge!(opts) cmd[:sort] = Mongo::Support.format_order_clause(opts[:sort]) if opts[:sort] full_response ? @db.command(cmd) : @db.command(cmd)['value'] end |
#find_one(spec_or_object_id = nil, opts = {}) ⇒ OrderedHash, Nil
Return a single object from the database.
306 307 308 309 310 311 312 313 314 315 316 317 318 |
# File 'lib/mongo/collection.rb', line 306 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.
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 |
# File 'lib/mongo/collection.rb', line 787 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 |
#index_information ⇒ Hash
Get information on the indexes for this collection.
958 959 960 |
# File 'lib/mongo/collection.rb', line 958 def index_information @db.index_information(@name) end |
#insert(doc_or_docs, opts = {}) ⇒ ObjectId, ... Also known as: <<
Insert one or more documents into the collection.
385 386 387 388 389 390 391 |
# File 'lib/mongo/collection.rb', line 385 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) } write_concern = get_write_concern(opts, self) result = insert_documents(doc_or_docs, @name, true, write_concern, opts) 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.
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 |
# File 'lib/mongo/collection.rb', line 733 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, (opts)) 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 |
#named_hint=(hint = nil) ⇒ Object
Set a hint field using a named index.
155 156 157 158 |
# File 'lib/mongo/collection.rb', line 155 def named_hint=(hint=nil) @hint = hint self end |
#options ⇒ Hash
Return a hash containing options that apply to this collection. For all possible keys and values, see DB#create_collection.
966 967 968 |
# File 'lib/mongo/collection.rb', line 966 def @db.collections_info(@name).next_document['options'] end |
#remove(selector = {}, opts = {}) ⇒ Hash, true
Remove all documents from this collection.
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 |
# File 'lib/mongo/collection.rb', line 422 def remove(selector={}, opts={}) write_concern = get_write_concern(opts, self) = BSON::ByteBuffer.new("\0\0\0\0", @connection.) 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 Mongo::WriteConcern.gle?(write_concern) @connection.(Mongo::Constants::OP_DELETE, , @db.name, nil, write_concern) 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.
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 |
# File 'lib/mongo/collection.rb', line 930 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.
339 340 341 342 343 344 345 346 347 |
# File 'lib/mongo/collection.rb', line 339 def save(doc, opts={}) if doc.has_key?(:_id) || doc.has_key?('_id') id = doc[:_id] || doc['_id'] update({:_id => id}, doc, opts.merge!({:upsert => true})) id else insert(doc, opts) end end |
#stats ⇒ Hash
Return stats on the collection. Uses MongoDB’s collstats command.
973 974 975 |
# File 'lib/mongo/collection.rb', line 973 def stats @db.command({:collstats => @name}) end |
#update(selector, document, opts = {}) ⇒ Hash, true
Update one or more documents in this collection.
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 |
# File 'lib/mongo/collection.rb', line 469 def update(selector, document, opts={}) # Initial byte is 0. write_concern = get_write_concern(opts, self) = BSON::ByteBuffer.new("\0\0\0\0", @connection.) BSON::BSON_RUBY.serialize_cstr(, "#{@db.name}.#{@name}") = 0 += 1 if opts[:upsert] += 2 if opts[:multi] # Determine if update document has modifiers and check keys if so check_keys = document.keys.first.to_s.start_with?("$") ? false : true .put_int() .put_binary(BSON::BSON_CODER.serialize(selector, false, true, @connection.max_bson_size).to_s) .put_binary(BSON::BSON_CODER.serialize(document, check_keys, true, @connection.max_bson_size).to_s) instrument(:update, :database => @db.name, :collection => @name, :selector => selector, :document => document) do if Mongo::WriteConcern.gle?(write_concern) @connection.(Mongo::Constants::OP_UPDATE, , @db.name, nil, write_concern) else @connection.(Mongo::Constants::OP_UPDATE, ) end end end |