简体   繁体   中英

PHP Query in MongoDB doesn't work

I have been trying to fix this problem since days and I can't really solve it.

I'm trying to use mongo DB for my first time and here's my problem:

$id = utf8_encode($_POST['mongo']);
$query=array("id" => $id);
$conn = new Mongo("mongodb://localhost:27017");
$database = $conn->test;
$collection = $database->pages;
$doc = $collection->findOne($query);

The $id variable is set to 2, but findOne doesn't return anything.

If I try for example to change the id value in array with 2 [$query=array("id" => 2);] the DB returns the document that I need.
It's a mystery ahah.
Can anyone see an error?
Thanks
L

After connect you should be select your document

$id = utf8_encode($_POST['mongo']);
$query=array("id" => $id);
$m = new MongoClient('mongodb://localhost:27017');
$db = $m->selectDB('yourdocumentname');
$collection = new MongoCollection($db, 'yourcollectionname');


$doc = $collection->findOne($query);
    var_dump($doc);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM