Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this update query only update one record once

Tags:

php

mongodb

$coll->update(
  array(
    "uid"=(int)$uid,
    "status"=>1,
    "time"=>array('$gt'=>0,'$lte'=>$time)
  ),
  array(
    '$set'=>array("status"=>0)
  )
);

If you can't read PHP, CLI version of above code:

db.we.update({"uid":1,"status":1,"time":{"$lte":1324403899}},{"$set":{status:0}})

where time is a timestamp integer, and status is int 0 or 1.

like image 708
dotslashlu Avatar asked Dec 10 '22 03:12

dotslashlu


2 Answers

This is the MongoDB default behaviour for updates. If you want to update multiple documents at once, you'll explicitly have to provide the multi flag:

db.collection.update( criteria, objNew, upsert, multi )

so you'd have to use

db.we.update({"uid":1, "status":1, "time" : {"$lte":1324403899}},
             {"$set":{status:0}}, 
             false, 
             true);

instead.

From the documentation:

If you are coming from SQL, be aware that by default, update() only modifies the first matched object. If you want to modify all matched objects, you need to use the multi flag.

like image 162
mnemosyn Avatar answered Dec 26 '22 22:12

mnemosyn


Now MongoDB is using updateMany to update multiple documents: db.collection.updateMany(, , )

    db.collection.updateMany(criteria, objNew)
like image 42
Jason Zhang Avatar answered Dec 26 '22 21:12

Jason Zhang