mongodb - Why can the documents referred to by a PHP MongoCursor object changes after a for each loop iterates through it? -


first explain situation, ask question.

situation:

assuming php mongodb database object "db" refers database has collection called "products". each document in our "products" collection looks this:

{    _id: <objectid>   upc_code: <int>   discontinued: <bool>   for_sale: <bool>   modified: <date> } 

imagine there thousands of these documents. imagine each, "discontinued" false, , "for_sale" true. modified dates not same.

step 1: search 100 oldest-modified products:

$newproducts = db->products->find(array('discontinued'=>false))->sort(array('modified'=>1))->limit(100); 

step 2: "for each" loop through $newproducts, , check each one's "upc_code" via api external web service. each product has been discontinued, update database, setting "discontinued" value true:

foreach($newproducts $product) {     $discontinued = checkapi($product['upc_code']);     if($discontinued) {         $update = array('$set'=>array('discontinued'=>true));         db->products->update->(array('_id'=>$product['_id']),$update);     } } 

step 3: after done, again iterate through $newproducts "for each" loop , make array of "_id" values:

$mongo_ids = array(); foreach($newproducts $product) {     $mongo_ids[] = $product['_id']; } 

step 4: update products "_id" values $in array, $set "modified" value current time:

$modified = myfunctiontogetcurrenttime(); $query = array('_id'=>array('$in'=>$mongo_ids)); $update2 = array('$set'=>array('modified'=>$modified));  $options = array('upsert'=>false,'multiple'=>true); db->products->update($query,$update2,$options); 

the problem none of products "discontinued" value got set true have "modified" property updated in step 4 because $products mongocursor object, , therefore in step 3 $products refers different set of documents in step 2, due fact in step 2, in of documents update value of same property mongocursor's query based on ("discontinued").

question:

therefore question is, firstly, why set of documents referred mongocursor object change this? there way "bake" it, documents found @ time of query don't change later? if there no way "bake" (so speak), best way store returned documents in variable not dynamic?

(note: know can $newproductsarray = iterator_to_array($newproducts) after step 1 store results of query in static variable. i'm more curious if there might way set mongocursor's options wouldn't necessary.)


Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -