MongoDB / PHP .. How to write individual queries?

How to write a search query in mongo db to select specific values. for instance

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

suppose if the MYSQL query looks like this

SELECT name,age from things where id=3;

I am wondering how to write a search request in PHP / MongoDB to select specific values?

+5
source share
5 answers
MySQL: SELECT name,age from things where id=3;  
Mongo: $db->things->find(array("id" => 3), array("name" => 1, "age" => 1));

You might want to use mongo _idinstead of your own created field id.

More details about php driver: http://php.net/manual/en/mongo.sqltomongo.php Another good link only for SQL to Mongo is http://rickosborne.org/download/SQL-to-MongoDB.pdf

+11
source
+1

using the mongo _id, .

:

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

PHP MongoDB, :

$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.

0
$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);
0

All Articles