解決 mongodb $in needs an array 問題


問題現象:

  在mongodb執行批量查詢操作時,拋出異常 Exception 2: $in needs an array。

問題解決:

  感謝偉大的 google 和 stackoverflow 有人遇到過該問題,問題的原因解釋得很清楚,偷個懶,直接 copy 過來,如下:

This... is a change in MongoDB 2.6.0, no longer accepting bson object in the $in clause.

This particular issue is being tracker as a PHP driver bug at https://jira.mongodb.org/browse/PHP-1051

The MongoDB PHP Driver will serialize an PHP Array into BSON Array (accepted by the $in operator) when the PHP array is: Sequential numerically indexed, starting from 0

This means that if you have an array like:

$array = array($id0, $id1, $id2, $id3, $id4);
and then you

unset($array[0]);
You actually wind up with:

$array = array(1 => $id1, 2 => $id2, 3 => $id3, 4 => $id);
Which does not start with index 0. The MongoDB PHP driver therefore converts this into a BSON Object... Leading to validation error in MongoDB as it expected an array.

Now, since the MongoDB PHP driver does not do parse your MongoDB query we cannot know which array should be exempted from this serialization rule.

The workaround is, as mentioned above, is to ensure your PHP arrays are numerically indexed, starting from 0. The easiest way to do that is to run

array_values($values);

 

  我英文水平一般般,屬於基本能看懂型,稍微解釋下,從 2.6.0 以后,mongodb 在使用 $in => xxx 這種形式的查詢的時候,不再支持 Bson 對象,而一個數組,如果索引不是以 0 開頭,那么 php 的 mongodb 的驅動就會默認將其轉化為 Bson 對象,從而導致批量查詢無法查詢。

  說這個問題的人也說了如何解決這個問題,就是使用  array_values($values) 生成一個索引從 0 開始的新數組即可。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM