Class: Moneta::Adapters::Mongo

Inherits:
Object
  • Object
show all
Includes:
Defaults, ExpiresSupport
Defined in:
lib/moneta/adapters/mongo.rb

Overview

MongoDB backend

Supports expiration, documents will be automatically removed starting with mongodb >= 2.2 (see docs.mongodb.org/manual/tutorial/expire-data/).

Instance Attribute Summary

Attributes included from ExpiresSupport

#default_expires

Instance Method Summary collapse

Methods included from Defaults

#[], #[]=, #close, #decrement, #fetch, #key?

Methods included from OptionSupport

#expires, #prefix, #raw, #with

Constructor Details

#initialize(options = {}) ⇒ Mongo

Returns a new instance of Mongo

Options Hash (options):

  • :collection (String) — default: 'moneta'

    MongoDB collection name

  • :host (String) — default: '127.0.0.1'

    MongoDB server host

  • :port (Integer) — default: MongoDB default port

    MongoDB server port

  • :db (String) — default: 'moneta'

    MongoDB database

  • :expires (Integer)

    Default expiration time


21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/moneta/adapters/mongo.rb', line 21

def initialize(options = {})
  self.default_expires = options.delete(:expires)
  collection = options.delete(:collection) || 'moneta'
  host = options.delete(:host) || '127.0.0.1'
  port = options.delete(:port) || ::Mongo::MongoClient::DEFAULT_PORT
  db = options.delete(:db) || 'moneta'
  connection = ::Mongo::MongoClient.new(host, port, options)
  @collection = connection.db(db).collection(collection)
  if connection.server_version >= '2.2'
    @collection.ensure_index([['expiresAt', ::Mongo::ASCENDING]], :expireAfterSeconds => 0)
  else
    warn 'You are using MongoDB version < 2.2, expired documents will not be deleted'
  end
end

Instance Method Details

#clear(options = {}) ⇒ void

This method returns an undefined value.

Clear all keys in this store


78
79
80
81
# File 'lib/moneta/adapters/mongo.rb', line 78

def clear(options = {})
  @collection.remove
  self
end

#delete(key, options = {}) ⇒ Object

Delete the key from the store and return the current value

Options Hash (options):

  • :raw (Boolean)

    Raw access without value transformation (See `Moneta::Transformer`)

  • :prefix (String)

    Prefix key (See `Moneta::Transformer`)

  • Other (Object)

    options as defined by the adapters or middleware


63
64
65
66
67
# File 'lib/moneta/adapters/mongo.rb', line 63

def delete(key, options = {})
  value = load(key, options)
  @collection.remove('_id' => ::BSON::Binary.new(key)) if value
  value
end

#increment(key, amount = 1, options = {}) ⇒ Object

Note:

Not every Moneta store implements this method, a NotImplementedError is raised if it is not supported.

Atomically increment integer value with key

This method also accepts negative amounts.


70
71
72
73
74
75
# File 'lib/moneta/adapters/mongo.rb', line 70

def increment(key, amount = 1, options = {})
  @collection.find_and_modify(:query => { '_id' => ::BSON::Binary.new(key) },
                              :update => { '$inc' => { 'value' => amount } },
                              :new => true,
                              :upsert => true)['value']
end

#load(key, options = {}) ⇒ Object

Fetch value with key. Return nil if the key doesn't exist

Options Hash (options):

  • :expires (Integer)

    Update expiration time (See `Moneta::Expires`)

  • :raw (Boolean)

    Raw access without value transformation (See `Moneta::Transformer`)

  • :prefix (String)

    Prefix key (See `Moneta::Transformer`)

  • Other (Object)

    options as defined by the adapters or middleware


37
38
39
40
41
42
43
44
45
46
47
# File 'lib/moneta/adapters/mongo.rb', line 37

def load(key, options = {})
  key = ::BSON::Binary.new(key)
  doc = @collection.find_one('_id' => key)
  if doc && (!doc['expiresAt'] || doc['expiresAt'] >= Time.now)
    expires = expires_at(options, nil)
    @collection.update({ '_id' => key },
                       # expiresAt must be a Time object (BSON date datatype)
                       { '$set' => { 'expiresAt' => expires || nil } }) if expires != nil
    doc['value'].to_s
  end
end

#store(key, value, options = {}) ⇒ Object

Store value with key

Options Hash (options):

  • :expires (Integer)

    Set expiration time (See `Moneta::Expires`)

  • :raw (Boolean)

    Raw access without value transformation (See `Moneta::Transformer`)

  • :prefix (String)

    Prefix key (See `Moneta::Transformer`)

  • Other (Object)

    options as defined by the adapters or middleware


50
51
52
53
54
55
56
57
58
59
60
# File 'lib/moneta/adapters/mongo.rb', line 50

def store(key, value, options = {})
  key = ::BSON::Binary.new(key)
  intvalue = value.to_i
  @collection.update({ '_id' => key },
                     { '_id' => key,
                       'value' => intvalue.to_s == value ? intvalue : ::BSON::Binary.new(value),
                       # expiresAt must be a Time object (BSON date datatype)
                       'expiresAt' => expires_at(options) || nil },
                     { :upsert => true })
  value
end