Mongodb – PHP/MongoDB: Unset all fields in a document

mongodbPHP

I want to use PHP to remove documents from a MongoDB collection, but it's a capped collection (and it's stuck that way until I can get more memory), which means I can't remove documents. I have to do the next best thing. How can I unset all the fields in a document?

$collection->update(array('name' => 'Amy'), array('$unset' => array(WHAT GOES HERE?)));

Of course, I could list all the fields I want to unset, but then I'd have to change the code any time a new field was added. Can I unset all fields without knowing the names of all the fields?

Best Answer

To remove all fields (aside from _id), you can just update with an empty document:

<?php
    $collection->update(array('name' => 'Amy'), array());
?>

That will update the document leaving only the _id field.

Note that this won't free up any of the preallocated space for your capped collection.