在mongoDB中查找具有ObjectID的文档
当我将一些文档插入集合(没有 ObjectID)时,mongoDB 添加了自己的 ObjectID。
我想通过唯一的 ObjectID 查询文档。
$db->collection_name->find(array('_id'=>'4e49fd8269fd873c0a000000')));
它不适用于“4e49fd8269fd873c0a000000”前面的 MongoID 或 ObjectID 前缀。
在 PHP 中使用 mongoDB 通过 ObjectID 查询的正确方法是什么?
When I inserted some documents into a collection (without an ObjectID) mongoDB adds its own ObjectIDs.
I want to query a document by its unique ObjectID.
$db->collection_name->find(array('_id'=>'4e49fd8269fd873c0a000000')));
It does not work either with prefix of MongoID or ObjectID in front of '4e49fd8269fd873c0a000000'.
What is the proper way to query by ObjectID with mongoDB in PHP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
很确定你必须使用
MongoId
对象,例如注释在 查询 页面上有点迟钝,但它确实提到...
Pretty sure you have to use a
MongoId
object, egThe notes on the Querying page are a little obtuse but it does mention...
我认为现在 API 更改为
MongoDB\BSON\ObjectID
,您也可以使用[]
来表示 PHP 5.4+ 中的数组,所以它应该是:基于 Phil 的回答。
I think now the API changes to
MongoDB\BSON\ObjectID
, also you can use[]
to denote an array in PHP 5.4+, so it should be:based on Phil's answer.
对于 MongoDB\Driver\Manager(MongoDB 的现代版本),您可以考虑以下工作代码:
出于测试目的:
For MongoDB\Driver\Manager, a modern version of a MongoDB, you might consider the following working code:
For testing purposes:
使用 alcaeus/mongo-php-adapter (在 php 7 下),需要将
\MongoId
转换为 BSON 类型:With alcaeus/mongo-php-adapter (under php 7), needed to convert
\MongoId
to BSON type: