简体   繁体   中英

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.

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:

$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. For examples where it's meant to be used, see the docs: http://docs.mongodb.org/manual/reference/operator/query/and .

There is slight difference between $and and , separated list of fields. MongoDB provides implicit and between all fields separated by , . The explicit $and is used when you want to same field multiple times in query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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