How to remove a document referenced by an id in mo

2019-01-20 06:51发布

问题:

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:

This is my document structure:

$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);

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

"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:"

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.

回答1:

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) ) );

Additional Information:

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' ) );

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' ) );

But instead you will need to use:

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

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'
);

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



回答2:

"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:"

Normally what the PHP manual states is true but not for you. You have changed the type of your _id to something other than an ObjectId (aka a MongoId).

With this in mind you need to search by that other object which is a MongoInt32:

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


回答3:

This should work:

$collection->deleteOne( array( '_id' => new MongoDB\BSON\ObjectId ($_id )) );


标签: php mongodb