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.
-
#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.
-
#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 |
# 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.delete(:pk)|| BSON::ObjectId @hint = nil @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.
80 81 82 83 |
# File 'lib/jmongo/collection.rb', line 80 def [](name) new_name = "#{self.name}.#{name}" @db.collection(new_name, @opts) end |
#capped? ⇒ Boolean
85 86 87 |
# File 'lib/jmongo/collection.rb', line 85 def capped? @j_collection.capped? end |
#count(opts = {}) ⇒ Integer Also known as: size
Get the number of documents in this collection.
641 642 643 644 645 646 647 648 |
# File 'lib/jmongo/collection.rb', line 641 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.
355 356 357 |
# File 'lib/jmongo/collection.rb', line 355 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.
585 586 587 588 589 590 591 592 |
# File 'lib/jmongo/collection.rb', line 585 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.
385 386 387 |
# File 'lib/jmongo/collection.rb', line 385 def drop @j_collection.drop end |
#drop_index(spec) ⇒ Object
Drop a specified index.
371 372 373 374 |
# File 'lib/jmongo/collection.rb', line 371 def drop_index(spec) raise MongoArgumentError, "Cannot drop index for nil name" unless name _drop_index(spec) end |
#drop_indexes ⇒ Object
Drop all indexes.
379 380 381 382 |
# File 'lib/jmongo/collection.rb', line 379 def drop_indexes # Note: calling drop_indexes with no args will drop them all. @j_collection.dropIndexes('*') end |
#ensure_index(spec, opts = {}) ⇒ Object
359 360 361 |
# File 'lib/jmongo/collection.rb', line 359 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.
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 174 175 176 177 178 179 180 181 182 |
# File 'lib/jmongo/collection.rb', line 149 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)
404 405 406 407 408 409 410 411 412 413 414 415 |
# File 'lib/jmongo/collection.rb', line 404 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.
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 |
# File 'lib/jmongo/collection.rb', line 199 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.
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 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 |
# File 'lib/jmongo/collection.rb', line 503 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
100 101 102 |
# File 'lib/jmongo/collection.rb', line 100 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.
95 96 97 98 |
# File 'lib/jmongo/collection.rb', line 95 def hint=(hint=nil) @hint = prep_hint(hint) self end |
#index_information ⇒ Hash
Get information on the indexes for this collection.
618 619 620 |
# File 'lib/jmongo/collection.rb', line 618 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.
249 250 251 252 253 254 255 256 257 258 259 |
# File 'lib/jmongo/collection.rb', line 249 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.
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 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 |
# File 'lib/jmongo/collection.rb', line 438 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.
626 627 628 629 |
# File 'lib/jmongo/collection.rb', line 626 def info = @db.collections_info(@name).to_a info.last['options'] end |
#remove(selector = {}, options = {}) ⇒ True
Remove all documents from this collection.
283 284 285 |
# File 'lib/jmongo/collection.rb', line 283 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.
602 603 604 605 606 607 608 609 610 611 |
# File 'lib/jmongo/collection.rb', line 602 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.message}" end end |
#safe ⇒ Object
65 66 67 |
# File 'lib/jmongo/collection.rb', line 65 def safe !!@opts.fetch(:safe, false) end |
#save(doc, options = {}) ⇒ ObjectID
Save a document to this collection.
230 231 232 |
# File 'lib/jmongo/collection.rb', line 230 def save(doc, ={}) save_document(doc, [:safe]) end |
#stats ⇒ Hash
Return stats on the collection. Uses MongoDB’s collstats command.
634 635 636 |
# File 'lib/jmongo/collection.rb', line 634 def stats @db.command({:collstats => @name}) end |
#update(selector, document, options = {}) ⇒ Object
Update a single document in this collection.
307 308 309 310 311 |
# File 'lib/jmongo/collection.rb', line 307 def update(selector, document, ={}) upsert, multi = !!([:upsert]), !!([:multi]) safe = .fetch(:safe, @opts[:safe]) update_documents(selector, document, upsert, multi, safe) end |