Вопрос

i have a problem for a simple select and update logic :

task = Task.queueing.where(conditions).order(:created_at.asc).first
if task
  task.set(:status=>2)
end

it's simple right ?

BUT, the problem is : 100+ requests coming in the same time have. SO many client got the same record, that's what i DONT want.

in mysql, i can do some thing like this to avoid duplicate load:

rnd_str = 10000000 * rand
Task.update(status:rnd_str).limit(1) # this may be wrong code
task = Task.where(status:rnd_str).first
task.set(status:2)
render :json=>task

BUT HOW TO UPDATE 1 RECORD WITH QUERY IN mongomapper ?

thx !

Это было полезно?

Решение

An update in MongoDB will only update one record by default. You have an option to update all the matching documents in a query with {multi:true} option but by default your update will only update one document.

So what you have to do is combine your "query" into your update statement so they execute atomically (just like you do it in SQL) and not do two separate operations. In shell syntax, something like:

   db.queueing.update({conditions}, {$set:{status:2}})

Now, if you also need the task document you updated to work with then you can use findAndModify to update and return the document in one atomic operation. Like this:

   task = db.queueing.findAndModify( {your-condition}, 
                                     sort: { your-ordering },
                                     update: { $set: { status: 2 } }
          } );
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top