[英]MongoDB/PHP.. How to write select queries?
How to write find query in mongo db to select certain values. 如何在mongo db中编写查找查询以选择某些值。 For example
例如
IN MYSQL - SELECT * from things where id=3;
IN Mongo - thingscollection->find(array("_id" => $id))
suppose if the MYSQL query looks like this, 假设MYSQL查询看起来像这样,
SELECT name,age from things where id=3;
I am wondering how to write find query in PHP/MongoDB to select specific values? 我想知道如何在PHP / MongoDB中编写查找查询以选择特定值?
MySQL: SELECT name,age from things where id=3;
Mongo: $db->things->find(array("id" => 3), array("name" => 1, "age" => 1));
You may want to use the mongo _id
instead of an own created id
field. 您可能希望使用mongo
_id
而不是自己创建的id
字段。
For more information specifically about the php driver: http://php.net/manual/en/mongo.sqltomongo.php An other good link for just SQL to Mongo is http://rickosborne.org/download/SQL-to-MongoDB.pdf 有关php驱动程序的更多信息: http : //php.net/manual/en/mongo.sqltomongo.php只有SQL到Mongo的另一个很好的链接是http://rickosborne.org/download/SQL-to- MongoDB.pdf
在Mongo语句中编写查询时,使用SQL作为参考。
您可以从PHP在线手册中找到SQL to Mongo Mapping Chart 。
Yogesh suggested using the mongo _id
but that actually is more complicated than a regular field in the document. Yogesh建议
using the mongo _id
但实际上比文档中的常规字段更复杂。
To achieve: 实现:
IN MYSQL - SELECT * from things where id=3;
using MongoDB's PHP driver, do this: 使用MongoDB的PHP驱动程序,执行以下操作:
$m = new MongoClient();
$db = $m->selectDB('stuff');
$collection = new MongoCollection($db, 'things');
$collection->find(array('_id', new MongoID('3'));
If you didn't save your document with an "_id" field, then Mongo adds this field automatically, with a BSON value that has a very high probability of being unique. 如果您没有使用“_id”字段保存文档,那么Mongo会自动添加此字段,其BSON值很有可能是唯一的。 It's usually something like '512ba941e0b975fe00000000'.
它通常类似于'512ba941e0b975fe00000000'。
If you try to $collection->find(array('_id' => '512ba941e0b975fe00000000'));
如果你尝试
$collection->find(array('_id' => '512ba941e0b975fe00000000'));
the results are empty and no error is generated, which can be extremely frustrating while debugging. 结果是空的,没有生成错误,这在调试时非常令人沮丧。 It's easy to forget to use
new MongoID()
and not simply the string _id
. 很容易忘记使用
new MongoID()
而不仅仅是字符串_id
。
$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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.