简体   繁体   English

PHP MongoDB使用MongoId对象_id查询一条记录

[英]PHP MongoDB query for one record using MongoId Object _id

I am currently learning MongoDB. 我目前正在学习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. 我想知道如何使用MongoId Object _id值在PHP中进行查询。 The closest answer to my question is at Perl Mongo find object Id . 与我的问题最接近的答案是在Perl Mongo查找对象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? 另外,有没有一种方法可以在创建新记录时将Object _id值记录在该记录的另一个字段中?

Thanks. 谢谢。

Update: 更新:

In addition to the answer I chose below, a coworker found this as well: 除了我在下面选择的答案外,同事还发现了这一点:

mongodb php findone() by ID mongodb php findone()通过ID

This should help, from the mongodb web site ( http://blog.mongodb.org/post/26903435041/mongodb-for-the-php-mind-part-2 ): 这应该从mongodb网站( 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? 关于您的问题的一部分,我不知道有任何自动方式将objectid存储在另一个字段中,但我也不知道您为什么要这样做-您已经将其存储在_id中,为什么要它在另一个领域?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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