0

设置,php + mongodb。

数据库应包含多个项目,其中“标题”包含“Apple”和“Orange”。我试图只获取同时包含“Apple”和“Orange”的项目。

  $regexOne = new MongoRegex( '/Apple/i' ); 
  $regexTwo = new MongoRegex('/Orange/i');

  $cursor = $collection->find( array( '$and' => array( array('Title' => $regexOne), array('Title' => $regexTwo) ) ) );

将 '$and' 替换为 '$or' 的相同查询可以正常工作(或至少看起来如此),但是尽管数据库中存在与这些条件匹配的数据,但这不会返回任何内容。

4

1 回答 1

1

呼应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",
  ),
)
于 2012-07-31T16:23:41.110 回答