在mongoDB中查找具有ObjectID的文档 [英] Find a document with ObjectID in mongoDB

查看:105
本文介绍了在mongoDB中查找具有ObjectID的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将一些文档插入到集合中(没有ObjectID)时,mongoDB添加了自己的ObjectID.

When I inserted some documents into a collection (without an ObjectID) mongoDB adds its own ObjectIDs.

我想通过其唯一的ObjectID查询文档.

I want to query a document by its unique ObjectID.

$db->collection_name->find(array('_id'=>'4e49fd8269fd873c0a000000')));

它不能在'4e49fd8269fd873c0a000000'前面加上MongoID或ObjectID前缀.

It does not work either with prefix of MongoID or ObjectID in front of '4e49fd8269fd873c0a000000'.

在PHP中使用mongoDB通过ObjectID查询的正确方法是什么?

What is the proper way to query by ObjectID with mongoDB in PHP?

推荐答案

请确保您必须使用 MongoId 对象,例如

Pretty sure you have to use a MongoId object, eg

$item = $collection->findOne(array(
    '_id' => new MongoId('4e49fd8269fd873c0a000000')));

查询页面上的注释有些晦涩,但确实提到了...

The notes on the Querying page are a little obtuse but it does mention...

除非用户另外指定,否则_id字段是MongoId.最常见的错误是试图使用字符串来匹配MongoId.请记住,这是两种不同的数据类型,并且不会以字符串"array()"与空数组不同的方式彼此匹配

Unless the user has specified otherwise, the _id field is a MongoId. The most common mistake is attepting to use a string to match a MongoId. Keep in mind that these are two different datatypes, and will not match each other in the same way that the string "array()" is not the same as an empty array

这篇关于在mongoDB中查找具有ObjectID的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆