解决 mongodb $in needs an array 问题

Posted talk is cheap, show me the cod

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解决 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 开始的新数组即可。

以上是关于解决 mongodb $in needs an array 问题的主要内容,如果未能解决你的问题,请参考以下文章

完美解决RuntimeError: one of the variables needed for gradient computation has been modified by an inp

python selenium error “Geckodriver executable needs to be in PATH”

python gevent 解决 (mach-o file, but is an incompatible architecture (have ‘x86_64‘, need ‘arm64‘))问题

mach-o file, but is an incompatible architecture (have ‘x86_64‘, need > ‘arm64e‘解决办法

mach-o file, but is an incompatible architecture (have ‘x86_64‘, need > ‘arm64e‘解决办法

mach-o file, but is an incompatible architecture (have ‘x86_64‘, need > ‘arm64e‘解决办法