【问题标题】:MongoDB/PHP.. How to write select queries?MongoDB/PHP ..如何编写选择查询?
【发布时间】:2012-09-12 17:15:10
【问题描述】:

如何在 mongo db 中编写查找查询以选择某些值。例如

IN MYSQL - SELECT * from things where id=3;
IN Mongo - thingscollection->find(array("_id" => $id))

假设 MYSQL 查询看起来像这样,

SELECT name,age from things where id=3;

我想知道如何在 PHP/MongoDB 中编写查找查询来选择特定值?

【问题讨论】:

标签: php mysql mongodb select


【解决方案1】:
MySQL: SELECT name,age from things where id=3;  
Mongo: $db->things->find(array("id" => 3), array("name" => 1, "age" => 1));

您可能希望使用 mongo _id 而不是自己创建的 id 字段。

有关 php 驱动程序的详细信息:http://php.net/manual/en/mongo.sqltomongo.php 另一个仅将 SQL 连接到 Mongo 的好链接是 http://rickosborne.org/download/SQL-to-MongoDB.pdf

【讨论】:

    【解决方案2】:

    在 Mongo 语句中编写查询时使用 SQL to Mongo 作为参考。

    【讨论】:

      【解决方案3】:

      您可能会发现 PHP 在线手册中的 SQL to Mongo Mapping Chart 很有帮助。

      【讨论】:

      【解决方案4】:

      Yogesh 建议使用 using the mongo _id,但实际上这比文档中的常规字段更复杂。

      实现:

      IN MYSQL - SELECT * from things where id=3;
      

      使用 MongoDB 的 PHP 驱动程序,执行以下操作:

      $m = new MongoClient();
      $db = $m->selectDB('stuff');
      $collection = new MongoCollection($db, 'things');
      $collection->find(array('_id', new MongoID('3'));
      

      如果您没有使用“_id”字段保存您的文档,那么 Mongo 会自动添加此字段,并且 BSON 值很可能是唯一的。它通常类似于“512ba941e0b975fe00000000”。

      如果你尝试$collection->find(array('_id' => '512ba941e0b975fe00000000'));,结果是空的并且不会产生错误,这在调试时会非常令人沮丧。很容易忘记使用new MongoID() 而不仅仅是字符串_id。

      【讨论】:

      • 不,您也可以使用$collection->find(array('_id' => '512ba941e0b975fe00000000'));。没有问题。
      【解决方案5】:
      $mongo_url = 'mongodb://127.0.0.1/';
      $client = new \MongoDB\Client($mongo_url);
      $db_name = 'your_db_name';
      $db = $client->$db_name;
      $collection = $db->your_collection_name;
      
      $where = array(
          'user_id' => 3
      );
      $select_fields = array(
          'name' => 1,
          'age' => 1,
      );
      $options = array(
          'projection' => $select_fields
      );
      $cursor = $collection->find($where, $options);   //This is the main line
      $docs = $cursor->toArray();
      
      print_r($docs);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-09
        • 1970-01-01
        • 2015-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多