Class: XGen::Mongo::Driver::Collection

Inherits:
Object
  • Object
show all
Defined in:
lib/mongo/collection.rb

Overview

A named collection of records in a database.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(db, name) ⇒ Collection

Returns a new instance of Collection.



28
29
30
31
# File 'lib/mongo/collection.rb', line 28

def initialize(db, name)
  @db, @name = db, name
  @hint = nil
end

Instance Attribute Details

#dbObject (readonly)

Returns the value of attribute db.



26
27
28
# File 'lib/mongo/collection.rb', line 26

def db
  @db
end

#hintObject

Returns the value of attribute hint.



26
27
28
# File 'lib/mongo/collection.rb', line 26

def hint
  @hint
end

#nameObject (readonly)

Returns the value of attribute name.



26
27
28
# File 'lib/mongo/collection.rb', line 26

def name
  @name
end

Instance Method Details

#clearObject

Remove all records.



102
103
104
# File 'lib/mongo/collection.rb', line 102

def clear
  remove({})
end

#count(selector = {}) ⇒ Object

Return the number of records that match selector. If selector is nil or an empty hash, returns the count of all records.



211
212
213
# File 'lib/mongo/collection.rb', line 211

def count(selector={})
  @db.count(@name, selector || {})
end

#create_index(field_or_spec, unique = false) ⇒ Object

Create a new index. field_or_spec should be either a single field name or a Array of [field name, direction] pairs. Directions should be specified as XGen::Mongo::ASCENDING or XGen::Mongo::DESCENDING. unique is an optional boolean indicating whether this index should enforce a uniqueness constraint.



131
132
133
# File 'lib/mongo/collection.rb', line 131

def create_index(field_or_spec, unique=false)
  @db.create_index(@name, field_or_spec, unique)
end

#dropObject

Drop the entire collection. USE WITH CAUTION.



147
148
149
# File 'lib/mongo/collection.rb', line 147

def drop
  @db.drop_collection(@name)
end

#drop_index(name) ⇒ Object

Drop index name.



136
137
138
# File 'lib/mongo/collection.rb', line 136

def drop_index(name)
  @db.drop_index(@name, name)
end

#drop_indexesObject

Drop all indexes.



141
142
143
144
# File 'lib/mongo/collection.rb', line 141

def drop_indexes
  # just need to call drop indexes with no args; will drop them all
  @db.drop_index(@name, '*')
end

#find(selector = {}, options = {}) ⇒ Object

Return records that match a selector hash. See Mongo docs for details.

Options:

:fields

Array of collection field names; only those will be returned (plus _id if defined)

:offset

Start at this record when returning records

:limit

Maximum number of records to return

:sort

Either hash of field names as keys and 1/-1 as values; 1 == ascending, -1 == descending, or array of field names (all assumed to be sorted in ascending order).

:hint

See #hint. This option overrides the collection-wide value.

Raises:

  • (RuntimeError)


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/mongo/collection.rb', line 52

def find(selector={}, options={})
  fields = options.delete(:fields)
  fields = nil if fields && fields.empty?
  offset = options.delete(:offset) || 0
  limit = options.delete(:limit) || 0
  sort = options.delete(:sort)
  hint = options.delete(:hint)
  if hint
    hint = normalize_hint_fields(hint)
  else
    hint = @hint        # assumed to be normalized already
  end
  raise RuntimeError, "Unknown options [#{options.inspect}]" unless options.empty?
  @db.query(self, Query.new(selector, fields, offset, limit, sort, hint))
end

#find_first(selector = {}, options = {}) ⇒ Object

Find the first record that matches selector. See #find.



69
70
71
72
73
74
# File 'lib/mongo/collection.rb', line 69

def find_first(selector={}, options={})
  h = options.dup
  h[:limit] = 1
  cursor = find(selector, h)
  cursor.next_object    # don't need to explicitly close b/c of limit
end

#group(keys, condition, initial, reduce) ⇒ Object

Perform a query similar to an SQL group by operation.

Returns an array of grouped items.

:keys

list of fields to group by

:condition

specification of rows to be considered (as a ‘find’ query specification)

:initial

initial value of the aggregation counter object

:reduce

aggregation function as a JavaScript string



160
161
162
163
164
165
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
# File 'lib/mongo/collection.rb', line 160

def group(keys, condition, initial, reduce)
  group_function = <<EOS
function () {
    var c = db[ns].find(condition);
    var map = new Map();
    var reduce_function = #{reduce};
    while (c.hasNext()) {
var obj = c.next();

var key = {};
for (var i in keys) {
    key[keys[i]] = obj[keys[i]];
}

var aggObj = map.get(key);
if (aggObj == null) {
    var newObj = Object.extend({}, key);
    aggObj = Object.extend(newObj, initial);
    map.put(key, aggObj);
}
reduce_function(obj, aggObj);
    }
    return {"result": map.values()};
}
EOS
  return @db.eval(Code.new(group_function,
                           {
                             "ns" => @name,
                             "keys" => keys,
                             "condition" => condition,
                             "initial" => initial
                           }))["result"]
end

#index_informationObject

Get information on the indexes for the collection collection_name. Returns a hash where the keys are index names (as returned by Collection#create_index and the values are lists of [key, direction] pairs specifying the index (as passed to Collection#create_index).



198
199
200
# File 'lib/mongo/collection.rb', line 198

def index_information
  @db.index_information(@name)
end

#insert(*objects) ⇒ Object Also known as: <<

Insert objects, which are hashes. “<<” is aliased to this method. Returns either the single inserted object or a new array containing objects. The object(s) may have been modified by the database’s PK factory, if it has one.



89
90
91
92
93
# File 'lib/mongo/collection.rb', line 89

def insert(*objects)
  objects = objects.first if objects.size == 1 && objects.first.is_a?(Array)
  res = @db.insert_into_db(@name, objects)
  res.size > 1 ? res : res.first
end

#modify(selector, modifier_obj) ⇒ Object

Update records that match selector by applying obj as an update. Both selector and modifier_obj are required.



119
120
121
122
123
# File 'lib/mongo/collection.rb', line 119

def modify(selector, modifier_obj)
  raise "no object" unless modifier_obj
  raise "no selector" unless selector
  @db.modify_in_db(@name, selector, modifier_obj)
end

#optionsObject

Return a hash containing options that apply to this collection. ‘create’ will be the collection name. For the other possible keys and values, see DB#create_collection.



205
206
207
# File 'lib/mongo/collection.rb', line 205

def options
  @db.collections_info(@name).next_object()['options']
end

#remove(selector = {}) ⇒ Object

Remove the records that match selector.



97
98
99
# File 'lib/mongo/collection.rb', line 97

def remove(selector={})
  @db.remove_from_db(@name, selector)
end

#replace(selector, obj) ⇒ Object

Update records that match selector by applying obj as an update.



113
114
115
# File 'lib/mongo/collection.rb', line 113

def replace(selector, obj)
  @db.replace_in_db(@name, selector, obj)
end

#repsert(selector, obj) ⇒ Object

Update records that match selector by applying obj as an update. If no match, inserts (???).



108
109
110
# File 'lib/mongo/collection.rb', line 108

def repsert(selector, obj)
  @db.repsert_in_db(@name, selector, obj)
end

#save(object) ⇒ Object

Save an updated object to the collection, or insert it if it doesn’t exist already.



77
78
79
80
81
82
83
# File 'lib/mongo/collection.rb', line 77

def save(object)
  if id = object[:_id] || object['_id']
    repsert({:_id => id}, object)
  else
    insert(object)
  end
end