呼应dimo414 所说的,第一步只是将 Mongo 的 shell 与 PHP 进行比较。这两个是等价的:
$ mongo
MongoDB shell version: 2.2.0-rc0
connecting to: test
> db.foo.drop()
true
> db.foo.insert({title:"apple"})
> db.foo.insert({title:"orange"})
> db.foo.insert({title:"apple orange"})
> db.foo.insert({title:"banana apple"})
> db.foo.insert({title:"banana plum"})
> db.foo.find({$and: [{title:/apple/i}, {title:/orange/i}]})
{ "_id" : ObjectId("501804c4e7dc9abd7b58cd83"), "title" : "apple orange" }
> db.foo.find({$or: [{title:/apple/i}, {title:/orange/i}]})
{ "_id" : ObjectId("501804bde7dc9abd7b58cd81"), "title" : "apple" }
{ "_id" : ObjectId("501804c0e7dc9abd7b58cd82"), "title" : "orange" }
{ "_id" : ObjectId("501804c4e7dc9abd7b58cd83"), "title" : "apple orange" }
{ "_id" : ObjectId("501804cce7dc9abd7b58cd84"), "title" : "banana apple" }
在 PHP 中(使用phpsh):
php> $c = (new Mongo())->test->foo;
php> =iterator_to_array($c->find(['$and' => [['title' => new MongoRegex('/apple/i')], ['title' => new MongoRegex('/orange/i')]]]))
array(
"501804c4e7dc9abd7b58cd83" => array(
"_id" => <object #10 of type MongoId> {
$id => "501804c4e7dc9abd7b58cd83",
},
"title" => "apple orange",
),
)
php> =iterator_to_array($c->find(['$or' => [['title' => new MongoRegex('/apple/i')], ['title' => new MongoRegex('/orange/i')]]]))
array(
"501804bde7dc9abd7b58cd81" => array(
"_id" => <object #11 of type MongoId> {
$id => "501804bde7dc9abd7b58cd81",
},
"title" => "apple",
),
"501804c0e7dc9abd7b58cd82" => array(
"_id" => <object #12 of type MongoId> {
$id => "501804c0e7dc9abd7b58cd82",
},
"title" => "orange",
),
"501804c4e7dc9abd7b58cd83" => array(
"_id" => <object #13 of type MongoId> {
$id => "501804c4e7dc9abd7b58cd83",
},
"title" => "apple orange",
),
"501804cce7dc9abd7b58cd84" => array(
"_id" => <object #14 of type MongoId> {
$id => "501804cce7dc9abd7b58cd84",
},
"title" => "banana apple",
),
)