Class: EM::Mongo::Collection
- Inherits:
-
Object
- Object
- EM::Mongo::Collection
- Defined in:
- lib/em-mongo/prev.rb,
lib/em-mongo/collection.rb
Instance Attribute Summary collapse
-
#connection ⇒ Object
Returns the value of attribute connection.
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.
-
#count ⇒ EM::Mongo::RequestResponse
(also: #size)
Get the number of documents in this collection.
-
#create_index(spec, opts = {}) ⇒ String
The name of the index created.
-
#db ⇒ EM::Mongo::Database
The database that this collection belongs to.
-
#distinct(key, query = nil) ⇒ EM::Mongo::RequestResponse
Return a list of distinct values for
key
across 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.
-
#find(selector = {}, opts = {}) ⇒ EM::Mongo::Cursor
Query the database.
-
#find_and_modify(opts = {}) ⇒ EM::Mongo::RequestResponse
Atomically update and return a document using MongoDB’s findAndModify command.
-
#find_one(spec_or_object_id = nil, opts = {}) ⇒ EM::Mongo::RequestResponse
(also: #first)
Return a single object from the database.
-
#group(opts = {}) ⇒ EM::Mongo::RequestResponse
Perform a group aggregation.
-
#index_information ⇒ EM::Mongo::RequestResponse
Get information on the indexes for this collection.
-
#initialize(db, ns, connection = nil) ⇒ Collection
constructor
Initialize a collection object.
-
#insert(doc_or_docs) ⇒ ObjectId, Array
(also: #<<)
Insert one or more documents into the collection.
-
#map_reduce(map, reduce, opts = {}) ⇒ EM::Mongo::RequestResponse
(also: #mapreduce)
Perform a map-reduce operation on the current collection.
-
#name ⇒ String
The name of this collection.
- #new_find ⇒ Object
-
#remove(selector = {}, opts = {}) ⇒ true
Remove all documents from this collection.
-
#safe_insert(doc_or_docs, safe_opts = {}) ⇒ EM::Mongo::RequestResponse
Insert one or more documents into the collection, with a failure if the operation doesn’t succeed Unlike insert, this method returns a deferrable.
-
#safe_save(doc, opts = {}) ⇒ EM::Mongo::RequestResponse
Calls backw with the _id of the saved document.
-
#safe_update(selector, document, opts = {}) ⇒ Hash, true
Returns a Hash containing the last error object if running in safe mode.
-
#save(doc, opts = {}) ⇒ ObjectId
Save a document to this collection.
-
#stats ⇒ EM::Mongo::RequestResponse
Return stats on the collection.
-
#update(selector, document, opts = {}) ⇒ Hash, true
Update one or more documents in this collection.
Constructor Details
#initialize(db, ns, connection = nil) ⇒ Collection
Initialize a collection object.
12 13 14 15 16 17 |
# File 'lib/em-mongo/collection.rb', line 12 def initialize(db, ns, connection = nil) @db = db || "db" @ns = ns || "ns" @name = [@db,@ns].join('.') @connection = connection || EM::Mongo::Connection.new end |
Instance Attribute Details
#connection ⇒ Object
Returns the value of attribute connection.
3 4 5 |
# File 'lib/em-mongo/collection.rb', line 3 def connection @connection 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.
39 40 41 42 |
# File 'lib/em-mongo/collection.rb', line 39 def [](name) name = "#{self.name}.#{name}" db.collection(name) 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.
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 |
# File 'lib/em-mongo/collection.rb', line 437 def aggregate(pipeline=nil, opts={}) response = RequestResponse.new 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 cmd_resp = db.command(hash) cmd_resp.callback do |resp| response.succeed resp["result"] end cmd_resp.errback do |err| response.fail err end response end |
#count ⇒ EM::Mongo::RequestResponse Also known as: size
Get the number of documents in this collection.
627 628 629 |
# File 'lib/em-mongo/collection.rb', line 627 def count find().count end |
#create_index(spec, opts = {}) ⇒ String
Returns the name of the index created.
693 694 695 696 697 698 699 700 701 |
# File 'lib/em-mongo/collection.rb', line 693 def create_index(spec, opts={}) 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 |
#db ⇒ EM::Mongo::Database
The database that this collection belongs to
21 22 23 |
# File 'lib/em-mongo/collection.rb', line 21 def db connection.db(@db) end |
#distinct(key, query = nil) ⇒ EM::Mongo::RequestResponse
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.
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 |
# File 'lib/em-mongo/collection.rb', line 544 def distinct(key, query=nil) raise MongoArgumentError unless [String, Symbol].include?(key.class) response = RequestResponse.new command = BSON::OrderedHash.new command[:distinct] = @ns command[:key] = key.to_s command[:query] = query cmd_resp = db.command(command) cmd_resp.callback do |resp| response.succeed resp["values"] end cmd_resp.errback do |err| response.fail err end response end |
#drop ⇒ Object
Drop the entire collection. USE WITH CAUTION.
369 370 371 |
# File 'lib/em-mongo/collection.rb', line 369 def drop db.drop_collection(@ns) end |
#drop_index(name) ⇒ Object
Drop a specified index.
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 |
# File 'lib/em-mongo/collection.rb', line 708 def drop_index(name) if name.is_a?(Array) response = RequestResponse.new name_resp = index_name(name) name_resp.callback do |name| drop_resp = db.drop_index(@ns, name) drop_resp.callback { response.succeed } drop_resp.errback { |err| response.fail(err) } end name_resp.errback { |err| response.fail(err) } response else db.drop_index(@ns, name) end end |
#drop_indexes ⇒ Object
Drop all indexes.
727 728 729 730 |
# File 'lib/em-mongo/collection.rb', line 727 def drop_indexes # Note: calling drop_indexes with no args will drop them all. db.drop_index(@ns, '*') end |
#find(selector = {}, opts = {}) ⇒ EM::Mongo::Cursor
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”.
97 98 99 100 101 102 103 |
# File 'lib/em-mongo/collection.rb', line 97 def find(selector={}, opts={}, &blk) raise "find requires a block" if not block_given? new_find(selector, opts).defer_as_a.callback do |docs| blk.call(docs) end end |
#find_and_modify(opts = {}) ⇒ EM::Mongo::RequestResponse
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 399 400 401 402 |
# File 'lib/em-mongo/collection.rb', line 387 def find_and_modify(opts={}) response = RequestResponse.new cmd = BSON::OrderedHash.new cmd[:findandmodify] = @ns cmd.merge!(opts) cmd[:sort] = EM::Mongo::Support.format_order_clause(opts[:sort]) if opts[:sort] cmd_resp = db.command(cmd) cmd_resp.callback do |doc| response.succeed doc['value'] end cmd_resp.errback do |err| response.fail err end response end |
#find_one(spec_or_object_id = nil, opts = {}) ⇒ EM::Mongo::RequestResponse Also known as: first
Return a single object from the database.
155 156 157 158 159 160 161 162 163 164 165 166 167 |
# File 'lib/em-mongo/collection.rb', line 155 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 = {}) ⇒ EM::Mongo::RequestResponse
Perform a group aggregation.
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 |
# File 'lib/em-mongo/collection.rb', line 578 def group(opts={}) response = RequestResponse.new reduce = opts[:reduce] finalize = opts[:finalize] cond = opts.fetch(:cond, {}) initial = opts[:initial] if !(reduce && initial) raise MongoArgumentError, "Group requires at minimum values for initial and reduce." end cmd = { "group" => { "ns" => @ns, "$reduce" => reduce.to_bson_code, "cond" => cond, "initial" => initial } } if finalize cmd['group']['finalize'] = finalize.to_bson_code end if key = opts[:key] if key.is_a?(String) || key.is_a?(Symbol) key = [key] end key_value = {} key.each { |k| key_value[k] = 1 } cmd["group"]["key"] = key_value elsif keyf = opts[:keyf] cmd["group"]["$keyf"] = keyf.to_bson_code end cmd_resp = db.command(cmd) cmd_resp.callback do |result| response.succeed result["retval"] end cmd_resp.errback do |err| response.fail err end response end |
#index_information ⇒ EM::Mongo::RequestResponse
Get information on the indexes for this collection.
644 645 646 |
# File 'lib/em-mongo/collection.rb', line 644 def index_information db.index_information(@ns) end |
#insert(doc_or_docs) ⇒ ObjectId, Array Also known as: <<
Insert one or more documents into the collection.
181 182 183 |
# File 'lib/em-mongo/collection.rb', line 181 def insert(doc_or_docs) safe_insert(doc_or_docs, :safe => false).data end |
#map_reduce(map, reduce, opts = {}) ⇒ EM::Mongo::RequestResponse Also known as: mapreduce
Perform a map-reduce operation on the current collection.
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 |
# File 'lib/em-mongo/collection.rb', line 487 def map_reduce(map, reduce, opts={}) response = RequestResponse.new 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'] = @ns hash['map'] = map hash['reduce'] = reduce hash.merge! opts cmd_resp = db.command(hash) cmd_resp.callback do |result| if EM::Mongo::Support.ok?(result) == false response.fail [Mongo::OperationFailure, "map-reduce failed: #{result['errmsg']}"] elsif raw response.succeed result elsif result["result"] response.succeed db.collection(result["result"]) else response.fail [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 cmd_resp.errback do |err| response.fail(err) end response end |
#name ⇒ String
The name of this collection
27 28 29 |
# File 'lib/em-mongo/collection.rb', line 27 def name @ns end |
#new_find ⇒ Object
5 |
# File 'lib/em-mongo/prev.rb', line 5 alias :new_find :find |
#remove(selector = {}, opts = {}) ⇒ true
Remove all documents from this collection.
358 359 360 361 362 363 364 365 366 |
# File 'lib/em-mongo/collection.rb', line 358 def remove(selector={}, opts={}) # Initial byte is 0. = BSON::ByteBuffer.new("\0\0\0\0") BSON::BSON_RUBY.serialize_cstr(, "#{@db}.#{@ns}") .put_int(0) .put_binary(BSON::BSON_CODER.serialize(selector, false, true).to_s) @connection.send_command(EM::Mongo::OP_DELETE, ) true end |
#safe_insert(doc_or_docs, safe_opts = {}) ⇒ EM::Mongo::RequestResponse
Insert one or more documents into the collection, with a failure if the operation doesn’t succeed Unlike insert, this method returns a deferrable
206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
# File 'lib/em-mongo/collection.rb', line 206 def safe_insert(doc_or_docs, safe_opts = {}) response = RequestResponse.new safe_opts[:safe] = true unless safe_opts[:safe] == false doc_or_docs = [doc_or_docs] unless doc_or_docs.is_a?(Array) doc_or_docs.map! { |doc| sanitize_id!(doc) } insert_resp = insert_documents(doc_or_docs, @ns, true, safe_opts) insert_resp.callback do |ids| ids.length > 1 ? response.succeed(ids) : response.succeed(ids[0]) end insert_resp.errback do |err| response.fail err end response end |
#safe_save(doc, opts = {}) ⇒ EM::Mongo::RequestResponse
Returns Calls backw with the _id of the saved document.
323 324 325 326 327 328 329 330 331 332 |
# File 'lib/em-mongo/collection.rb', line 323 def safe_save(doc, opts={}) opts[:safe] = true unless opts[:safe] == false id = has_id?(doc) sanitize_id!(doc) if id safe_update({:_id => id}, doc, opts.merge(:upsert => true)) else safe_insert(doc, opts) end end |
#safe_update(selector, document, opts = {}) ⇒ Hash, true
Returns a Hash containing the last error object if running in safe mode. Otherwise, returns true.
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 |
# File 'lib/em-mongo/collection.rb', line 270 def safe_update(selector, document, opts={}) response = RequestResponse.new opts = opts.dup opts[:safe] = true unless opts[:safe] == false # Initial byte is 0. = BSON::ByteBuffer.new("\0\0\0\0") BSON::BSON_RUBY.serialize_cstr(, "#{@db}.#{@ns}") = 0 += 1 if opts.delete(:upsert) += 2 if opts.delete(:multi) .put_int() .put_binary(BSON::BSON_CODER.serialize(selector, false, true).to_s) .put_binary(BSON::BSON_CODER.serialize(document, false, true).to_s) if opts[:safe] send_resp = safe_send(EM::Mongo::OP_UPDATE, , true, opts) send_resp.callback { response.succeed(true) } send_resp.errback { |err| response.fail(err) } else @connection.send_command(EM::Mongo::OP_UPDATE, ) response.succeed(true) end response end |
#save(doc, opts = {}) ⇒ ObjectId
Save a document to this collection.
304 305 306 |
# File 'lib/em-mongo/collection.rb', line 304 def save(doc, opts={}) safe_save(doc, opts.merge(:safe => false)).data end |
#stats ⇒ EM::Mongo::RequestResponse
Return stats on the collection. Uses MongoDB’s collstats command.
635 636 637 |
# File 'lib/em-mongo/collection.rb', line 635 def stats @db.command({:collstats => @name}) end |
#update(selector, document, opts = {}) ⇒ Hash, true
Update one or more documents in this collection.
240 241 242 243 |
# File 'lib/em-mongo/collection.rb', line 240 def update(selector, document, opts={}) # Initial byte is 0. safe_update(selector, document, opts.merge(:safe => false)).data end |