Class: Mongo::Collection
- Includes:
- JavaImpl::Collection_, JavaImpl::Utils
- Defined in:
- lib/jmongo/collection.rb
Constant Summary
Constants included from JavaImpl::Utils
Instance Attribute Summary collapse
-
#db ⇒ Object
readonly
Returns the value of attribute db.
-
#j_collection ⇒ Object
readonly
Returns the value of attribute j_collection.
-
#j_db ⇒ Object
readonly
Returns the value of attribute j_db.
-
#name ⇒ Object
readonly
Returns the value of attribute name.
-
#pk_factory ⇒ Object
readonly
Returns the value of attribute pk_factory.
Instance Method Summary collapse
-
#[](name) ⇒ Collection
Return a sub-collection of this collection by name.
- #capped? ⇒ Boolean
-
#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) ⇒ Array
Return a list of distinct values for
key
across all documents in the collection. -
#drop ⇒ Object
Drop the entire collection.
-
#drop_index(spec) ⇒ Object
Drop a specified index.
-
#drop_indexes ⇒ Object
Drop all indexes.
- #ensure_index(spec, opts = {}) ⇒ Object
-
#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.
- #hint ⇒ Object
-
#hint=(hint = nil) ⇒ Object
Set a hint field for query optimizer.
-
#index_information ⇒ Hash
Get information on the indexes for this collection.
-
#initialize(*args) ⇒ Collection
constructor
Initialize a collection object.
-
#insert(doc_or_docs, options = {}) ⇒ ObjectID, Array
(also: #<<)
Insert one or more documents into the collection.
-
#map_reduce(map, reduce, opts = {}) ⇒ Collection
(also: #mapreduce)
Perform a map/reduce operation on the current collection.
- #monitor_collection ⇒ Object
- #monitor_subscribe(opts, &callback_doc) ⇒ Object
- #monitored_collection ⇒ Object
-
#options ⇒ Hash
Return a hash containing options that apply to this collection.
-
#remove(selector = {}, options = {}) ⇒ True
Remove all documents from this collection.
-
#rename(new_name) ⇒ Object
Rename this collection.
- #safe ⇒ Object
-
#save(doc, options = {}) ⇒ ObjectID
Save a document to this collection.
- #setup_monitor ⇒ Object
-
#stats ⇒ Hash
Return stats on the collection.
-
#update(selector, document, options = {}) ⇒ Object
Update a single document in this collection.
Methods included from JavaImpl::Utils
#from_dbobject, #prep_fields, #prep_hint, #prep_id, #prep_sort, #raise_not_implemented, #sort_value, #system_name?, #to_dbobject, #trap_raise, #validate_name
Constructor Details
#initialize(*args) ⇒ Collection
Initialize a collection object.
db, name, options=nil, j_collection=nil
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/jmongo/collection.rb', line 39 def initialize(*args) j_collection = nil @opts = {} if args.size == 4 j_collection = args.pop end if args.size == 3 @opts = args.pop end if args.size < 2 raise ArgumentError.new("Must supply at least name and db parameters") end if args.first.is_a?(String) name, db = args else db, name = args end @name = validate_name(name) @db, @j_db = db, db.j_db @connection = @db.connection @pk_factory = @opts.delete(:pk)|| BSON::ObjectId @hint = nil @monitor = @opts.delete(:monitor) if @monitor setup_monitor elsif @opts.has_key?(:monitor_source) @monitor_source = @opts.delete(:monitor_source) end @j_collection = j_collection || @j_db.create_collection(@name, to_dbobject(@opts)) end |
Instance Attribute Details
#db ⇒ Object (readonly)
Returns the value of attribute db.
22 23 24 |
# File 'lib/jmongo/collection.rb', line 22 def db @db end |
#j_collection ⇒ Object (readonly)
Returns the value of attribute j_collection.
21 22 23 |
# File 'lib/jmongo/collection.rb', line 21 def j_collection @j_collection end |
#j_db ⇒ Object (readonly)
Returns the value of attribute j_db.
21 22 23 |
# File 'lib/jmongo/collection.rb', line 21 def j_db @j_db end |
#name ⇒ Object (readonly)
Returns the value of attribute name.
22 23 24 |
# File 'lib/jmongo/collection.rb', line 22 def name @name end |
#pk_factory ⇒ Object (readonly)
Returns the value of attribute pk_factory.
22 23 24 |
# File 'lib/jmongo/collection.rb', line 22 def pk_factory @pk_factory 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.
97 98 99 100 |
# File 'lib/jmongo/collection.rb', line 97 def [](name) new_name = "#{self.name}.#{name}" @db.collection(new_name, @opts) end |
#capped? ⇒ Boolean
102 103 104 |
# File 'lib/jmongo/collection.rb', line 102 def capped? @j_collection.capped? end |
#count(opts = {}) ⇒ Integer Also known as: size
Get the number of documents in this collection.
658 659 660 661 662 663 664 665 |
# File 'lib/jmongo/collection.rb', line 658 def count(opts={}) return @j_collection.count() if opts.empty? query = opts[:query] || opts['query'] || {} fields = opts[:fields] || opts['fields'] || {} limit = opts[:limit] || opts['limit'] || 0 skip = opts[:skip] || opts['skip'] || 0 @j_collection.get_count(to_dbobject(query), to_dbobject(fields), limit, skip) end |
#create_index(spec, opts = {}) ⇒ String
Create a new index.
372 373 374 |
# File 'lib/jmongo/collection.rb', line 372 def create_index(spec, opts={}) _create_index(spec, opts) 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.
602 603 604 605 606 607 608 609 |
# File 'lib/jmongo/collection.rb', line 602 def distinct(key, query=nil) raise MongoArgumentError unless [String, Symbol].include?(key.class) if query from_dbobject @j_collection.distinct(key.to_s, to_dbobject(query)) else from_dbobject @j_collection.distinct(key.to_s) end end |
#drop ⇒ Object
Drop the entire collection. USE WITH CAUTION.
402 403 404 |
# File 'lib/jmongo/collection.rb', line 402 def drop @j_collection.drop end |
#drop_index(spec) ⇒ Object
Drop a specified index.
388 389 390 391 |
# File 'lib/jmongo/collection.rb', line 388 def drop_index(spec) raise MongoArgumentError, "Cannot drop index for nil name" unless name _drop_index(spec) end |
#drop_indexes ⇒ Object
Drop all indexes.
396 397 398 399 |
# File 'lib/jmongo/collection.rb', line 396 def drop_indexes # Note: calling drop_indexes with no args will drop them all. @j_collection.dropIndexes('*') end |
#ensure_index(spec, opts = {}) ⇒ Object
376 377 378 |
# File 'lib/jmongo/collection.rb', line 376 def ensure_index(spec, opts={}) _ensure_index(spec, opts) 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.
166 167 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 |
# File 'lib/jmongo/collection.rb', line 166 def find(selector={}, opts={}) fields = prep_fields(opts.delete(:fields)) 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, "Timeout can be set to false only when #find is invoked with a block." end if hint hint = prep_hint(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, :batch_size => batch_size, :timeout => timeout, :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)
421 422 423 424 425 426 427 428 429 430 431 432 |
# File 'lib/jmongo/collection.rb', line 421 def find_and_modify(opts={}) query = opts[:query] || {} fields = opts[:fields] || {} sort = prep_sort(opts[:sort] || []) update = opts[:update] || {} remove = opts[:remove] || false new_ = opts[:new] || false upsert = opts[:upsert] || false trap_raise(OperationFailure) do find_and_modify_document(query, fields, sort, remove, update, new_, upsert) end end |
#find_one(spec_or_object_id = nil, opts = {}) ⇒ OrderedHash, Nil
Return a single object from the database.
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 |
# File 'lib/jmongo/collection.rb', line 216 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 begin find_one_document(spec, opts) rescue => ex raise OperationFailure, ex. end end |
#group(opts, condition = {}, initial = {}, reduce = nil, finalize = nil) ⇒ Array
Perform a group aggregation.
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 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 567 568 569 570 571 572 573 574 575 |
# File 'lib/jmongo/collection.rb', line 520 def group(opts, condition={}, initial={}, reduce=nil, finalize=nil) key = keyf = false if opts.is_a?(Hash) reduce, finalize, initial= opts.values_at(:reduce, :finalize, :initial) key, keyf = opts.values_at(:key, :keyf) condition = opts.fetch(:cond, {}) unless key.nil? && keyf.nil? unless key.is_a?(Array) || keyf.is_a?(String) || keyf.is_a?(BSON::Code) 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 end 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" case opts when Array key = opts when String, BSON::Code keyf = opts else 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 end if !(reduce && initial) raise MongoArgumentError, "Group requires at minimum values for initial and reduce." end cmd = { "group" => { "ns" => @name, "$reduce" => reduce.to_bson_code, "cond" => condition, "initial" => initial } } if keyf cmd["group"]["$keyf"] = keyf.to_bson_code elsif key key_hash = Hash[key.zip( [1]*key.size )] cmd["group"]["key"] = key_hash end if finalize cmd['group']['finalize'] = finalize.to_bson_code end result = from_dbobject(@db.command(cmd)) return result["retval"] if Mongo.result_ok?(result) raise OperationFailure, "group command failed: #{result['errmsg']}" end |
#hint ⇒ Object
117 118 119 |
# File 'lib/jmongo/collection.rb', line 117 def hint @hint end |
#hint=(hint = nil) ⇒ Object
Set a hint field for query optimizer. Hint may be a single field name, array of field names, or a hash (preferably an [OrderedHash]). If using MongoDB > 1.1, you probably don’t ever need to set a hint.
112 113 114 115 |
# File 'lib/jmongo/collection.rb', line 112 def hint=(hint=nil) @hint = prep_hint(hint) self end |
#index_information ⇒ Hash
Get information on the indexes for this collection.
635 636 637 |
# File 'lib/jmongo/collection.rb', line 635 def index_information @db.index_information(@name) end |
#insert(doc_or_docs, options = {}) ⇒ ObjectID, Array Also known as: <<
Insert one or more documents into the collection.
266 267 268 269 270 271 272 273 274 275 276 |
# File 'lib/jmongo/collection.rb', line 266 def insert(doc_or_docs, ={}) doc_or_docs = [doc_or_docs] unless doc_or_docs.kind_of?(Array) doc_or_docs.collect! do |doc| @pk_factory.create_pk(doc) prep_id(doc) end safe = .fetch(:safe, @opts[:safe]) continue = ([:continue_on_error] || false) docs = insert_documents(doc_or_docs, safe, continue) docs.size == 1 ? docs.first['_id'] : docs.collect{|doc| doc['_id']} end |
#map_reduce(map, reduce, opts = {}) ⇒ Collection Also known as: mapreduce
Perform a map/reduce operation on the current collection.
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 |
# File 'lib/jmongo/collection.rb', line 455 def map_reduce(map, reduce, opts={}) query = opts.fetch(:query,{}) sort = opts.fetch(:sort,[]) limit = opts.fetch(:limit,0) finalize = opts[:finalize] out = opts[:out] keeptemp = opts.fetch(:keeptemp,true) verbose = opts.fetch(:verbose,true) raw = opts.delete(:raw) m = map.to_s r = reduce.to_s mrc = case out when String JMongo::MapReduceCommand.new(@j_collection, m, r, out, REPLACE, to_dbobject(query)) when Hash if out.keys.size != 1 raise ArgumentError, "You need to specify one key value pair in the out hash" end out_type = out.keys.first out_val = out[out_type] unless MapReduceEnumHash.keys.include?(out_type) raise ArgumentError, "Your out hash must have one of these keys: #{MapReduceEnumHash.keys}" end out_type_enum = MapReduceEnumHash[out_type] out_dest = out_val.is_a?(String) ? out_val : nil JMongo::MapReduceCommand.new(@j_collection, m, r, out_dest, out_type_enum, to_dbobject(query)) else raise ArgumentError, "You need to specify an out parameter in the options hash" end mrc.verbose = verbose mrc.sort = prep_sort(sort) mrc.limit = limit mrc.finalize = finalize result = from_dbobject(@j_db.command(mrc.toDBObject)) 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 |
#monitor_collection ⇒ Object
669 670 671 672 |
# File 'lib/jmongo/collection.rb', line 669 def monitor_collection raise InvalidOperation, "Monitoring has not been setup, add :monitor - true or Hash" unless @monitorable @mon_collection end |
#monitor_subscribe(opts, &callback_doc) ⇒ Object
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 |
# File 'lib/jmongo/collection.rb', line 678 def monitor_subscribe(opts, &callback_doc) raise MongoArgumentError, "Not a monitorable collection" if @monitor_source.nil? raise MongoArgumentError, "Must supply a block" unless block_given? raise MongoArgumentError, "opts needs to be a Hash" unless opts.is_a?(Hash) callback_exit = opts[:callback_exit] raise MongoArgumentError, "Need a callable for exit callback" unless callback_doc.respond_to?('call') exit_check_timeout = opts[:exit_check_timeout] raise MongoArgumentError, "Need a positive float for timeout" unless exit_check_timeout.to_f > 0.0 tail = Mongo::Cursor.new(self, :timeout => false, :tailable => true, :await_data => 0.5, :order => [['$natural', 1]]) loop_th = Thread.new(tail, callback_doc) do |cur, cb| while !Thread.current[:stop] doc = cur.next cb.call(doc) if doc end end loop_th[:stop] = false exit_th = Thread.new(exit_check_timeout.to_f, callback_exit) do |to, cb| while true sleep to must_exit = cb.call break if must_exit end loop_th[:stop] = true end # end |
#monitored_collection ⇒ Object
674 675 676 |
# File 'lib/jmongo/collection.rb', line 674 def monitored_collection @monitor_source end |
#options ⇒ Hash
Return a hash containing options that apply to this collection. For all possible keys and values, see DB#create_collection.
643 644 645 646 |
# File 'lib/jmongo/collection.rb', line 643 def info = @db.collections_info(@name).to_a info.last['options'] end |
#remove(selector = {}, options = {}) ⇒ True
Remove all documents from this collection.
300 301 302 |
# File 'lib/jmongo/collection.rb', line 300 def remove(selector={}, ={}) remove_documents(selector,[:safe]) end |
#rename(new_name) ⇒ Object
Rename this collection.
Note: If operating in auth mode, the client must be authorized as an admin to perform this operation.
619 620 621 622 623 624 625 626 627 628 |
# File 'lib/jmongo/collection.rb', line 619 def rename(new_name) _name = validate_name(new_name) begin jcol = @j_collection.rename(_name) @name = _name @j_collection = jcol rescue => ex raise MongoDBError, "Error renaming collection: #{name}, more: #{ex.}" end end |
#safe ⇒ Object
82 83 84 |
# File 'lib/jmongo/collection.rb', line 82 def safe !!@opts.fetch(:safe, false) end |
#save(doc, options = {}) ⇒ ObjectID
Save a document to this collection.
247 248 249 |
# File 'lib/jmongo/collection.rb', line 247 def save(doc, ={}) save_document(doc, [:safe]) end |
#setup_monitor ⇒ Object
72 73 74 75 76 77 78 79 80 |
# File 'lib/jmongo/collection.rb', line 72 def setup_monitor mon_opts = @monitor.is_a?(Hash)? @monitor : {} size = mon_opts.fetch(:size, 8000) @monitor_max = mon_opts.fetch(:max, 100) opts = {:capped => true, :max => @monitor_max, :size => size, :monitor_source => self} @mon_collection = @db.create_collection("#{@name}-monitor", opts) @j_mon_collection = @mon_collection.j_collection @monitorable = true end |
#stats ⇒ Hash
Return stats on the collection. Uses MongoDB’s collstats command.
651 652 653 |
# File 'lib/jmongo/collection.rb', line 651 def stats @db.command({:collstats => @name}) end |
#update(selector, document, options = {}) ⇒ Object
Update a single document in this collection.
324 325 326 327 328 |
# File 'lib/jmongo/collection.rb', line 324 def update(selector, document, ={}) upsert, multi = !!([:upsert]), !!([:multi]) safe = .fetch(:safe, @opts[:safe]) update_documents(selector, document, upsert, multi, safe) end |