PHP中MongoDB多个$and运算符查询
我在使用 PHP 数组语法进行 MongoDB 查询时遇到问题。这是我想使用的查询的直接版本。
db.collection.find({
$or: [
{$and : [{X:1}, {X: {$gt: 100}}]},
{$and : [{X:2}, {X: {$lt: 100}}]}
]
});
注意:真正的查询更复杂,这只是一个示例。
我无法找到一些在 PHP 中描述此类查询的示例。 我想到的最好的办法是:
$query = array(
'$or' => array(
array(
'$and' => array(
array('X' => 1),
array('X' => array('gt' => 100))
)
),
array(
'$and' => array(
array('X' => 2),
array('X' => array('lt' => 100))
)
),
)
);
$this->db->collection->find($query);
但是这个查询不返回任何结果。 显然我们不能从数组中删除 $and
因为 PHP 数组中不能有重复的键。
我不想使用 JavaScript 表达式,因为速度至关重要。
更新:正如亚历山大·阿扎罗夫在评论中指出的那样,我原来的查询可以用不同的方式编写。我已使用正确使用的 $and
查询更新了问题。
I’m having trouble with this MongoDB query using PHP array syntax. This is a direct version of the query I want to use.
db.collection.find({
$or: [
{$and : [{X:1}, {X: {$gt: 100}}]},
{$and : [{X:2}, {X: {$lt: 100}}]}
]
});
Note: The real query is more complicated, this is just an example.
I wasn’t able to find some examples describing this kind of query in PHP.
The best I’ve come up was this:
$query = array(
'$or' => array(
array(
'$and' => array(
array('X' => 1),
array('X' => array('gt' => 100))
)
),
array(
'$and' => array(
array('X' => 2),
array('X' => array('lt' => 100))
)
),
)
);
$this->db->collection->find($query);
But this query doesn't return any results.
Obviously we can't remove $and
from the array because we can't have duplicate keys in PHP array.
I don't want to use JavaScript expressions because the speed is critical.
UPDATE: As Alexander Azarov pointed out in comments, my original query can be written differently. I've updated the question with the properly used $and
query.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下是 PHP 中使用 or 和 and 运算符进行 Mongo 查询的代码示例。
它使用与您将在查询中找到的字段名称不同的字段名称,但很容易理解如何使用它。
现在我没有时间更改它来匹配您的查询,但如果您有问题,请告诉我,我会调整它。该查询正在运行并找到它应该找到的内容。
Here is an example of the code with or and and operators in PHP for a Mongo query.
It uses different field names from what you are going to find in your query, but it is straightforward to understand how to use it.
Right now I don't have time to change it, to match your query, but if you have problems with that, let me know and I will adjust it. This query is working and finding what it should find.