Question

I want to do something like

UPDATE tbl SET n=10 WHERE time>NOW()-INTERVAL 1 HOUR ORDER BY b DESC LIMIT 1

I tried

db.tbl.update({$query:{time:{$gt:new Date(new Date()-3600000)},
               $orderby:{b:-1},
               $limit:1},
              {$set:{n:10}})

but it didn't work. I was able to find the document using db.tbl.find({$query:...}) though.

Was it helpful?

Solution

There are actually two ways to work around (BTW, I think mongoDB should definitely fix this long-overdue problem in their next release).

  1. use forEach() after the find(). Instead of update() you can also use save(). The problem of this workaround is performance, as update/save need to search again.

    db.tbl.find({$query:...}).forEach(function(d){ db.tbl.update({_id:d._id},{$set:{n:10}}); })

  2. use findAndModify(). This only works for limit 1. If you need to update more than one document, then findAndModify() cannot do it.

    db.tbl.findAndModify({ query:{time:{$gt:new Date(new Date()-3600000)}}, sort:{b:-1}, update:{$set:{n:10}} })

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top