Akku
Akku

Reputation: 4454

PHP Copy a document in MongoDB, replacing it's MongoID

When changing a certain document where (it's unsure how exactly the structure is), I want to create a backup of this document in another collection before saving it back to my current collection. To do the backup, I tried this:

$mongoDbObj = $collection->findOne($filter);
...
$collectionBackup->insert($mongoDbObj,true);

... but this works only once because the MongoID is copied. When I try to backup the same document again, the MongoID already exists in the backupCollection. So my question is:

Can I copy a MongoDB document in PHP, overwriting the MongoID with a new MongoID, before inserting into another collection, without changing the MongoID of the original document?


This question simplified is: How can I do this:

$mongoDbObj = $collection->findOne($filter);
...
$collectionBackup->insert($mongoDbObj,true);
// change MongoId so the next line doesn't throw exception
$collectionBackup->insert($mongoDbObj,true);
// save my object back with the original MongoID
$collection->save($mongoDbObj);

Also helpful would be how to clone / copy a MongoDB document, then it would be easy to get around the problem by just sticking a new MongoID in a copied document.

Upvotes: 2

Views: 1575

Answers (2)

Xanarus
Xanarus

Reputation: 775

So you want to copy a document and duplicate it in an other collection without _id mongo .

Use fields query in order to remove fields you don't need.

Example :

$mongoDbObj = $collection->findOne($filter);
$mongoDbObj->fields(array("_id" => false));

Docs : http://www.php.net/manual/en/mongocursor.fields.php

Have fun :)

Upvotes: 1

Tobias Hinz
Tobias Hinz

Reputation: 26

$mongoDbObj = $collection->findOne($filter);
$mongoDbObjBak = array();

foreach($mongoDbObj as $key => $value) {
    if($key != '_id') {
        $mongoDbObjBak[$key] = $value;
    }
}

$collectionBackup->insert($mongoDbObjBak,true);
$collection->save($mongoDbObj);

Upvotes: 1

Related Questions