如何从PHP中删除mongoDB中ID引用的文档? [英] How to remove a document referenced by an id in mongoDB from php?

查看:40
本文介绍了如何从PHP中删除mongoDB中ID引用的文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我成功使用其他字段删除了文档,但无法使用"_id"字段删除. PHP页面说该id应该是一个字符串(默认情况下是字符串),但是我想做的是,给出一个我自己的ID(整数),然后执行以下操作:

I was successful in deleting documents using other fields but could not delete using "_id" field. The PHP page says that the id should be a string (which it is by default), but what I was trying to do is, giving an id of my own which is an integer, and am doing the following:

这是我的文档结构:

$document = array (
    '_id' => new MongoInt32(1),
    'cust_id' => 'abc124'
)

这就是我要删除的方式:

This is how I am trying to delete:

$collection->remove(array('_id' => new MongoId(1)), true);

但这给我一个错误. PHP php手册说:

But this is giving me an error. PHP php manual says:

要基于文档的ID删除文档,您需要确保将ID作为MongoID对象而不是字符串传递:"

"To remove a document based on its ID, you need to ensure that you pass the ID as a MongoID object rather than just a string:"

但是我的ID是一个i​​nt,我无法弄清楚删除该ID引用的文档的过程.

But my id is a int and I cant figure out the process to delete the document referenced by the id.

您的帮助将不胜感激.谢谢.

Your help would be appreciated. Thank You.

推荐答案

您已将普通整数(MongoInt32)用作_id字段.而且MongoInt32与MongoID不同.他们是两个不同的类.您应该使用以下命令将其删除:

You've used a normal integer (MongoInt32) as _id field. And MongoInt32 is not the same as MongoID. They are two different classes. You are suppose to delete it with:

$collection->remove( array( '_id' => new MongoInt32(1) ) );

其他信息:

MongoId作为_id字段的值:

MongoId is used as value for an _id field if you don't set a value yourself, such as with:

$collection->insert( array( 'cust_id' => 'abc124' ) );

如果您检索此文档以及var_dump(),将会看到:

If you retrieve this document, and var_dump() that you will see:

array(2) {
  '_id' =>
  class MongoId#6 (1) {
    public $$id =>
    string(24) "51ee74e944670a09028d4fc9"
  }
  'cust_id' =>
  string(6) "abc124"
}

文档中的注释表示您无法通过以下方式删除该文档:

The note in the docs mean that you can't remove that document now with:

$collection->remove( array( '_id' => '51ee74e944670a09028d4fc9' ) );

但是您需要使用:

$collection->remove( array( '_id' => new MongoID( '51ee74e944670a09028d4fc9' ) ) );

关于最后一点,我想提出的是,您实际上不必首先使用new MongoInt32(1),您可以使用:

As last point I'd like to raise that you don't really have to use new MongoInt32(1) in the first place, you can just use:

$document = array (
    '_id' => 1,
    'cust_id' => 'abc124'
);

如果您使用的是32位平台(或Windows),并且只需要处理大量数字,则只需要MongoInt32/MongoInt64.

You only need MongoInt32/MongoInt64 in case you're on a 32-bit platform (or Windows) and need to deal with large numbers.

这篇关于如何从PHP中删除mongoDB中ID引用的文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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