Colm Troy
Colm Troy

Reputation: 1947

Mongodb and Ruby gem - Check if record exists

I've a simple Ruby script (no rails, sinatra etc.) that uses the Mongo gem to insert records into my DB as part of a Redis/Resque worker.

Upon occasion instead of doing a fresh insert I'd like to update a counter field on an existing record. I can do this handily enough with rails/mysql. What's the quickest way of doing this in pure Ruby with Mongodb?

Thanks,

Ed

Upvotes: 0

Views: 1653

Answers (2)

Colm Troy
Colm Troy

Reputation: 1947

thanks to envu's direction I went with upsert in the end. here is an example snippet of how to use it the Ruby client:

    link_id = @globallinks.update(
      {
        ":url" => "http://somevalue.com"
      }, 
      {
        '$inc' => {":totalcount" => 1},
        '$set' => {":timelastseen" => Time.now}
      }, 
      {
        :upsert=>true
      }
    )  

Upvotes: 0

evnu
evnu

Reputation: 6680

The Ruby client library for MongoDB is very convenient and easy to use. So, to update a document in MongoDB, use something similar to this:

#!/usr/bin/ruby
require 'mongo'

database = Mongo::Connection.new.db("yourdatabasename")

# get the document
x = database.find({"_id" => "12312132"})

# change the document
x["count"] = (x["count"] || 0) + 1

# update it in mongodb
database["collection"].update("_id" => "thecollectionid", x)

You might want to check out the manual for updating documents in MongoDB as well.

Upvotes: 2

Related Questions