Class: Mongocore::Query

Inherits:
Object
  • Object
show all
Defined in:
lib/mongocore/query.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(m, q = {}, o = {}, s = {}) ⇒ Query

Mongocore query initializer



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/mongocore/query.rb', line 16

def initialize(m, q = {}, o = {}, s = {})

  # Storing model class. The instance can be found in store[:source]
  @model = m

  # The model name is singular, the collection name is plural
  @colname = m.to_s.downcase.pluralize.to_sym

  # Storing the Mongo::Collection object
  @collection = Mongocore.db[@colname]

  # Storing query and options
  s[:chain] ||= []; s[:source] ||= nil; s[:sort] ||= Mongocore.sort; s[:projection] ||= {}; s[:skip] ||= 0; s[:limit] ||= 0
  @query, @options, @store = @model.schema.ids(hashify(q)), o, s

  # Set up cache
  @cache = Mongocore::Cache.new(self)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *arguments, &block) ⇒ Object

Call and return the scope if it exists



190
191
192
193
# File 'lib/mongocore/query.rb', line 190

def method_missing(name, *arguments, &block)
  return @model.send(name, @query, @options, @store.tap{|r| r[:chain] << name}) if @model.schema.scopes.has_key?(name)
  super
end

Instance Attribute Details

#cacheObject

# # # # # # # The Query class keeps the cursor and handles the connection with the underlying MongoDB database. A new query is created every time you call find, sort, limit, count, update, scopes and associations.

Every query can be chained, but only one find is ever done to the database, it’s only the parameters that change.



13
14
15
# File 'lib/mongocore/query.rb', line 13

def cache
  @cache
end

#collectionObject

# # # # # # # The Query class keeps the cursor and handles the connection with the underlying MongoDB database. A new query is created every time you call find, sort, limit, count, update, scopes and associations.

Every query can be chained, but only one find is ever done to the database, it’s only the parameters that change.



13
14
15
# File 'lib/mongocore/query.rb', line 13

def collection
  @collection
end

#colnameObject

# # # # # # # The Query class keeps the cursor and handles the connection with the underlying MongoDB database. A new query is created every time you call find, sort, limit, count, update, scopes and associations.

Every query can be chained, but only one find is ever done to the database, it’s only the parameters that change.



13
14
15
# File 'lib/mongocore/query.rb', line 13

def colname
  @colname
end

#modelObject

# # # # # # # The Query class keeps the cursor and handles the connection with the underlying MongoDB database. A new query is created every time you call find, sort, limit, count, update, scopes and associations.

Every query can be chained, but only one find is ever done to the database, it’s only the parameters that change.



13
14
15
# File 'lib/mongocore/query.rb', line 13

def model
  @model
end

#optionsObject

# # # # # # # The Query class keeps the cursor and handles the connection with the underlying MongoDB database. A new query is created every time you call find, sort, limit, count, update, scopes and associations.

Every query can be chained, but only one find is ever done to the database, it’s only the parameters that change.



13
14
15
# File 'lib/mongocore/query.rb', line 13

def options
  @options
end

#queryObject

# # # # # # # The Query class keeps the cursor and handles the connection with the underlying MongoDB database. A new query is created every time you call find, sort, limit, count, update, scopes and associations.

Every query can be chained, but only one find is ever done to the database, it’s only the parameters that change.



13
14
15
# File 'lib/mongocore/query.rb', line 13

def query
  @query
end

#storeObject

# # # # # # # The Query class keeps the cursor and handles the connection with the underlying MongoDB database. A new query is created every time you call find, sort, limit, count, update, scopes and associations.

Every query can be chained, but only one find is ever done to the database, it’s only the parameters that change.



13
14
15
# File 'lib/mongocore/query.rb', line 13

def store
  @store
end

Instance Method Details

#allObject

Return all documents



100
101
102
# File 'lib/mongocore/query.rb', line 100

def all
  fetch(:to_a).map{|d| modelize(d)}
end

#as_json(o = {}) ⇒ Object

JSON format



180
181
182
# File 'lib/mongocore/query.rb', line 180

def as_json(o = {})
  all
end

#countObject

Count. Returns the number of documents as an integer



78
79
80
# File 'lib/mongocore/query.rb', line 78

def count
  counter || fetch(:count)
end

#counter(s = , c = ) ⇒ Object

Check if there’s a corresponding counter for this count



83
84
85
# File 'lib/mongocore/query.rb', line 83

def counter(s = @store[:source], c = @store[:chain])
  s.send(%{#{@colname}#{c.present? ? "_#{c.join('_')}" : ''}_count}) rescue nil
end

#cursorObject

Cursor



47
48
49
50
51
52
53
54
# File 'lib/mongocore/query.rb', line 47

def cursor
  c = @collection.find(@query, @options)
  c = c.sort(@store[:sort]) if @store[:sort].any?
  c = c.projection(@store[:projection]) if @store[:projection].any?
  c = c.skip(@store[:skip]) if @store[:skip] > 0
  c = c.limit(@store[:limit]) if @store[:limit] > 0
  c
end

#deleteObject

Delete



73
74
75
# File 'lib/mongocore/query.rb', line 73

def delete
  @collection.delete_one(@query).ok?
end

#each(&block) ⇒ Object

Each



139
140
141
# File 'lib/mongocore/query.rb', line 139

def each(&block)
  cursor.each{|r| yield(modelize(r))}
end

#each_with_index(&block) ⇒ Object

Each with index



144
145
146
# File 'lib/mongocore/query.rb', line 144

def each_with_index(&block)
  cursor.each_with_index{|r, n| yield(modelize(r), n)}
end

#each_with_object(obj, &block) ⇒ Object

Each with object



149
150
151
# File 'lib/mongocore/query.rb', line 149

def each_with_object(obj, &block)
  cursor.each_with_object(obj){|r, o| yield(modelize(r), o)}
end

#fetch(t) ⇒ Object

Fetch docs, pass type :first, :to_a or :count



131
132
133
134
135
136
# File 'lib/mongocore/query.rb', line 131

def fetch(t)
  cache.get(t) if Mongocore.cache

  # Fetch from mongodb and add to cache
  cursor.send(t).tap{|r| cache.set(t, r) if Mongocore.cache}
end

#find(q = {}, o = {}, s = {}) ⇒ Object Also known as: where

Find. Returns a Mongocore::Query



36
37
38
# File 'lib/mongocore/query.rb', line 36

def find(q = {}, o = {}, s = {})
  self.class.new(@model, @query.merge(hashify(q)), @options.merge(o), @store.merge(s))
end

#first(*args) ⇒ Object

Return first document



88
89
90
# File 'lib/mongocore/query.rb', line 88

def first(*args)
  modelize(find(*args).fetch(:first))
end

#hashify(q) ⇒ Object

Convert string query to hash



42
43
44
# File 'lib/mongocore/query.rb', line 42

def hashify(q)
  q.is_a?(Hash) ? q : {:_id => q}
end

#insert(a) ⇒ Object

Insert



57
58
59
# File 'lib/mongocore/query.rb', line 57

def insert(a)
  @collection.insert_one(a.delete_if{|k, v| v.nil?})
end

#keyObject

Cache key



185
186
187
# File 'lib/mongocore/query.rb', line 185

def key
  @key ||= "#{@model}#{@query.sort}#{@options.sort}#{@store.values}"
end

#last(*args) ⇒ Object

Return last document Uses the opposite of the Mongocore.sort setting



94
95
96
97
# File 'lib/mongocore/query.rb', line 94

def last(*args)
  a = Mongocore.sort.any? ? Mongocore.sort.dup : {:_id => 1}
  sort(a.each{|k, v| a[k] = v * -1}).limit(1).first(*args)
end

#limit(n = 1) ⇒ Object

Limit



164
165
166
# File 'lib/mongocore/query.rb', line 164

def limit(n = 1)
  find(@query, @options, @store.tap{store[:limit] = n})
end

#map(&block) ⇒ Object

Map



154
155
156
# File 'lib/mongocore/query.rb', line 154

def map(&block)
  cursor.map{|r| yield(modelize(r))}
end

#modelize(doc) ⇒ Object

BSON::Document to model



126
127
128
# File 'lib/mongocore/query.rb', line 126

def modelize(doc)
  doc ? @model.new(doc.to_hash) : nil
end

#paginate(o = {}) ⇒ Object

Paginate



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/mongocore/query.rb', line 105

def paginate(o = {})
  # Get total count before applying pagination
  total = fetch(:count)

  # Set page, defaults to 1
  o[:page] = o[:page].to_i; o[:page] = 1 if o[:page] < 1

  # Set results per page, defaults to 20 in Mongocore.per_page setting
  o[:per_page] = o[:per_page].to_i; o[:per_page] = Mongocore.per_page if o[:per_page] < 1

  # Skip results
  @store[:skip] = o[:per_page] * (o[:page] - 1)

  # Apply limit
  @store[:limit] = o[:per_page]

  # Fetch the result as array
  all.tap{|r| r.total = total}
end

#projection(o = {}) ⇒ Object Also known as: fields

Projection



174
175
176
# File 'lib/mongocore/query.rb', line 174

def projection(o = {})
  find(@query, @options, @store.tap{store[:projection].merge!(o)})
end

#skip(n = 0) ⇒ Object

Skip



169
170
171
# File 'lib/mongocore/query.rb', line 169

def skip(n = 0)
  find(@query, @options, @store.tap{store[:skip] = n})
end

#sort(o = {}) ⇒ Object

Sort



159
160
161
# File 'lib/mongocore/query.rb', line 159

def sort(o = {})
  find(@query, @options, @store.tap{(store[:sort] ||= {}).merge!(o)})
end

#update(a) ⇒ Object

Update



62
63
64
65
66
67
68
69
70
# File 'lib/mongocore/query.rb', line 62

def update(a)
  # We do $set on non nil, $unset on nil
  u = {
    :$set => a.select{|k, v| !v.nil?}, :$unset => a.select{|k, v| v.nil?}
  }.delete_if{|k, v| v.empty?}

  # Update the collection
  @collection.update_one(@query, u, :upsert => true)
end