简体   繁体   English

PHP中的MongoDB查询:为什么要使用$ and?

[英]MongoDB query in PHP: why use $and?

I'm learning MongoDB for the first time and am a little confused about writing queries with multiple arguments. 我是第一次学习MongoDB,对编写带有多个参数的查询有些困惑。

Considering the following temp collection 考虑以下临时集合

$col = (new MongoClient())->selectDB('tmpDB')->selectCollection('tmpCol');

$colors = ['red', 'blue', 'green', 'yellow', 'pink', 'orange', 'purple', 'gray'];
$objects = ['lamps', 'flowers', 'balloons', 'french horns', 'gables', 'slips', 'flamingos', 'streets'];

for ($i=0; $i < 100; ++$i) {
    $collection->insert([
        'count' => mt_rand(1, 99),
        'color' => $colors[mt_rand(0, count($colors)-1)],
        'object' => $objects[mt_rand(0, count($objects)-1)],
    ]);
}

I want to write a query that will find all of the documents with red balloons . 我想编写一个查询,以查找所有带有红色气球的文档。 I've read over the MongoDB core docs and come up with two queries: 我已经阅读了MongoDB核心文档,并提出了两个查询:

$col->count(['color' => 'red', 'object' => 'balloons']);

or 要么

$col->count(['$and' => [['color' => 'red'], ['object' => 'balloons']]]);

Both queries seem to work. 这两个查询似乎都有效。 Acknowledging that my data-set is fairly small, both queries return the correct result in roughly the same time. 承认我的数据集很小,两个查询在大约同一时间返回正确的结果。 I'm not sure if there is a difference that I am missing, or if these statements are actually equivalent? 我不确定我是否缺少区别,或者这些语句是否实际上等效? What is the best practice? 最佳做法是什么?

In your case they are equivalent. 在您的情况下,它们是等效的。 $and on top level is implied. $and在顶层。 For examples where it's meant to be used, see the docs: http://docs.mongodb.org/manual/reference/operator/query/and . 有关应使用该示例的示例,请参阅文档: http : //docs.mongodb.org/manual/reference/operator/query/and

There is slight difference between $and and , separated list of fields. 之间存在细微的差别$and,分隔的字段列表。 MongoDB provides implicit and between all fields separated by , . MongoDB在所有由,分隔的字段之间提供隐式和。 The explicit $and is used when you want to same field multiple times in query. 当您要在查询中多次访问同一字段时$and将使用显式$and

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM