Method: Moped::Query#modify

Defined in:
lib/moped/query.rb

#modify(change, options = {}) ⇒ Hash

Execute a $findAndModify on the query.

Examples:

Find and modify a document, returning the original.

db[:bands].find.modify({ "$inc" => { likes: 1 }})

Find and modify a document, returning the updated document.

db[:bands].find.modify({ "$inc" => { likes: 1 }}, new: true)

Find and return a document, removing it from the database.

db[:bands].find.modify({}, remove: true)

Find and return a document, upserting if no match found.

db[:bands].find.modify({}, upsert: true, new: true)

Parameters:

  • change (Hash)

    The changes to make to the document.

  • options (Hash) (defaults to: {})

    The options.

Options Hash (options):

  • :new (Object)

    Set to true if you want to return the updated document.

  • :remove (Object)

    Set to true if the document should be deleted.

  • :upsert (Object)

    Set to true if you want to upsert

Returns:

  • (Hash)

    The document.

Since:

  • 1.0.0



245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/moped/query.rb', line 245

def modify(change, options = {})
  command = {
    findAndModify: collection.name,
    query: selector
  }.merge(options)

  command[:sort] = operation.selector["$orderby"] if operation.selector["$orderby"]
  command[:fields] = operation.fields if operation.fields
  command[:update] = change unless options[:remove]

  result = session.with(consistency: :strong) do |sess|
    sess.command(command)["value"]
  end

  # Keeping moped compatibility with mongodb >= 2.2.0-rc0
  options[:upsert] && !result ? {} : result
end