简体   繁体   中英

PHP MongoDB query for one record using MongoId Object _id

I am currently learning MongoDB. I have seen tutorials for querying a field in a collection. I would like to know how to query in PHP using the MongoId Object _id value. The closest answer to my question is at Perl Mongo find object Id .

Also, is there a way that when a new record is created, the Object _id value can be recorded in another field of that record?

Thanks.

Update:

In addition to the answer I chose below, a coworker found this as well:

mongodb php findone() by ID

This should help, from the mongodb web site ( http://blog.mongodb.org/post/26903435041/mongodb-for-the-php-mind-part-2 ):

// This is only a string, this is NOT a MongoId
$mongoid = '4cb4ab6d7addf98506010000';

// You will not find anything by searching by string alone
$nothing = $collection->find(array('_id' => $mongoid));
echo $nothing->count(); // This should echo 0

// THIS is how you find something by MongoId
$realmongoid = new MongoId($mongoid);

// Pass the actual instance of the MongoId object to the query
$something = $collection->find(array('_id' => $realmongoid));
echo $something->count(); // This should echo 1

Regarding part of your question, I'm not aware of any automated way to store the objectid in another field but I'm also not aware of why you would want to do that - you already have it stored in _id, why would you want it in another field?

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