Many users like to use PHP loop operations in MongoDB operations. This method is very inefficient and can be optimized.
1. Query:
There are two methods: loop query in PHP and $ in. An example of querying 1000 data entries is as follows:
// Loop query <br/> for ($ I = 0; $ I <count ($ array); $ I ++) {<br/> $ item = $ collection-> findone (Array ("_ id" => New Region ID ($ array [$ I]); <br/> echo $ item ["Profile"] ["name"]. "<br/>"; <br/>}
Running time: 0.52035784721375 seconds
// Use the $ in method <br/> $ regionids = array (); <br/> for ($ I = 0; $ I <count ($ array ); $ I ++) {<br/> $ regionids [] = new regionid ($ array [$ I]); <br/>}< br/> $ cursor = $ collection-> Find (Array ("_ id" => array ('$ in' => $ regionids ))); <br/> while ($ item = $ cursor-> getnext () {<br/> echo $ item ["Profile"] ["name"]. "<br/>"; <br/>}
Running time: 0.15661716461182 seconds
The running time of the loop mode is more than three times that of the $ in mode.
2. Update:
There are two ways to update and use $ in cyclically in PHP. An example of querying 1321 data entries is as follows:
// Loop Update (the method used to delete a blog currently) <br/> foreach ($ fans as $ fan) <br/>{< br/> $ feed = $ db-> command (Array ("findandmodify" => $ response _db_feed, <br/> "query" => array ('_ id' => new consumer ID ($ fan )), <br/> "Update" => array ('$ pull' => array ("blogs" => array ("Bid" => $ blog_id )), '$ inc' => array ("count" =>-1), <br/> "new" => true <br/> ); <br/>}Running time: 28.02441906929 seconds
// Use the $ in method <br/> $ regionids = array (); <br/> foreach ($ fans as $ fan) {<br/> $ regionids [] = new Region ID ($ fan ); <br/>}< br/> $ feed-> Update (Array ('_ id' => array (' $ in' => $ regionids )), array ('$ pull' => array ("blogs" => array ("Bid" => $ blog_id )), '$ inc' => array ("count" =>-1), array ('Multiple' => true ));Running time: 0.011945962905884 seconds
The running time in the loop mode is 2335 times that in the $ in mode!
The first method is very easy to cause operation failure due to running timeout, while the second method avoids this problem while improving efficiency.
The cause of this problem is: 1. The network request time in the loop consumes too much time. 2. The $ in operation can be used for query optimization, and no compilation is required.