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.
-
#hint ⇒ Object
Returns the value of attribute hint.
-
#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
(also: #ensure_index)
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.
-
#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(*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.
-
#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.
-
#save(doc, options = {}) ⇒ ObjectID
Save a document to this collection.
-
#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_sort, #raise_not_implemented, #sort_value, #to_dbobject, #trap_raise
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 |
# 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.respond_to?('collection_names') db, name = args else name, db = args end @name = validate_name(name) @db, @j_db = db, db.j_db @connection = @db.connection @pk_factory = @opts[:pk] || BSON::ObjectId @hint = nil @j_collection = j_collection || @j_db.get_collection(@name) 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 |
#hint ⇒ Object
Returns the value of attribute hint.
22 23 24 |
# File 'lib/jmongo/collection.rb', line 22 def hint @hint 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.
76 77 78 79 80 |
# File 'lib/jmongo/collection.rb', line 76 def [](name) new_name = "#{self.name}.#{name}" validate_name new_name @db.create_collection(new_name, @opts) end |
#capped? ⇒ Boolean
82 83 84 |
# File 'lib/jmongo/collection.rb', line 82 def capped? @j_collection.isCapped end |
#count(opts = {}) ⇒ Integer Also known as: size
Get the number of documents in this collection.
625 626 627 628 629 630 631 632 |
# File 'lib/jmongo/collection.rb', line 625 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 Also known as: ensure_index
Create a new index.
341 342 343 |
# File 'lib/jmongo/collection.rb', line 341 def create_index(spec, opts={}) _create_indexes(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.
568 569 570 571 572 573 574 575 |
# File 'lib/jmongo/collection.rb', line 568 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.
368 369 370 |
# File 'lib/jmongo/collection.rb', line 368 def drop @j_collection.drop end |
#drop_index(spec) ⇒ Object
Drop a specified index.
354 355 356 357 |
# File 'lib/jmongo/collection.rb', line 354 def drop_index(spec) raise MongoArgumentError, "Cannot drop index for nil name" unless name _drop_index(spec) end |
#drop_indexes ⇒ Object
Drop all indexes.
362 363 364 365 |
# File 'lib/jmongo/collection.rb', line 362 def drop_indexes # Note: calling drop_indexes with no args will drop them all. @j_collection.dropIndexes('*') 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.
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 |
# File 'lib/jmongo/collection.rb', line 140 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 = 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, :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)
387 388 389 390 391 392 393 394 395 396 397 398 |
# File 'lib/jmongo/collection.rb', line 387 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.
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 |
# File 'lib/jmongo/collection.rb', line 190 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.
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 |
# File 'lib/jmongo/collection.rb', line 486 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 |
#index_information ⇒ Hash
Get information on the indexes for this collection.
601 602 603 |
# File 'lib/jmongo/collection.rb', line 601 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.
240 241 242 243 244 245 246 |
# File 'lib/jmongo/collection.rb', line 240 def insert(doc_or_docs, ={}) doc_or_docs = [doc_or_docs] unless doc_or_docs.kind_of?(Array) doc_or_docs.collect! { |doc| @pk_factory.create_pk(doc) } 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.
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 |
# File 'lib/jmongo/collection.rb', line 421 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 |
#options ⇒ Hash
Return a hash containing options that apply to this collection. For all possible keys and values, see DB#create_collection.
609 610 611 612 613 |
# File 'lib/jmongo/collection.rb', line 609 def info = @db.collections_info(@name).to_a ap info info.last['options'] end |
#remove(selector = {}, options = {}) ⇒ True
Remove all documents from this collection.
270 271 272 |
# File 'lib/jmongo/collection.rb', line 270 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.
585 586 587 588 589 590 591 592 593 594 |
# File 'lib/jmongo/collection.rb', line 585 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 |
#save(doc, options = {}) ⇒ ObjectID
Save a document to this collection.
221 222 223 |
# File 'lib/jmongo/collection.rb', line 221 def save(doc, ={}) save_document(doc, [:safe]) end |
#stats ⇒ Hash
Return stats on the collection. Uses MongoDB’s collstats command.
618 619 620 |
# File 'lib/jmongo/collection.rb', line 618 def stats @db.command({:collstats => @name}) end |
#update(selector, document, options = {}) ⇒ Object
Update a single document in this collection.
294 295 296 297 |
# File 'lib/jmongo/collection.rb', line 294 def update(selector, document, ={}) upsert, multi = !!([:upsert]), !!([:multi]) update_documents(selector, document, upsert, multi, [:safe]) end |