使用mongodb的$和php

时间:2012-07-31 15:19:27

标签: php mongodb database

设置,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) ) ) );

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

1 个答案:

答案 0 :(得分:1)

回应dimo414 said的内容,第一步是简单地将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",
  ),
)