Created
July 4, 2013 10:07
-
-
Save spacemonkey/5926512 to your computer and use it in GitHub Desktop.
This is a simple PHP script that solves the common problem of folks forgetting to add created_at (MongoDate) to all of their documents. This script will get a list of your collections and loop through them, only updating documents that are missing a created_at property; and these are fixed by pulling the date out of the _id object, and convertin…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* add_create_date.php by Spacemonkey | |
* https://gist.github.com/spacemonkey | |
* | |
* Loops through all collections in a mongodb database, | |
* finds all documents that are missing a created_at property | |
* and extracts it from _id and updates the document. | |
* | |
* As this is executed only on documents missing the created_at | |
* property, you can run it over and over on the same database. | |
**/ | |
echo "ALL RIGHTY THEN! LET'S GET THIS PARTY STARTED.\n\n\n"; | |
// CONFIGURATION | |
$config_host = 'localhost'; // This is your database host | |
$config_db = 'database'; // This is your database name | |
/** | |
* You should not need to edit anything below this line. | |
**/ | |
$m = new mongoClient("mongodb://$config_host"); | |
$db = $m->selectDB($config_db); | |
// List of collections | |
$collections = $db->getCollectionNames(); | |
// Set the query options, only find documents missing created_at property | |
$options = array( | |
'created_at' => array( '$exists' => false ) | |
); | |
// Loop through collections, adding created_at if missing | |
foreach($collections AS $collection){ | |
echo "********************\nWORKING ON: $collection\n"; | |
$c = $db->$collection->find($options); | |
echo "There are " . $c->count() . " documents in this collection without the 'created_at' property.\n"; | |
foreach($c AS $doc){ | |
// Get proper MongoId object | |
$id = $doc["_id"]; | |
$mongoid = new MongoId($id); | |
// Set created_at property | |
$doc['created_at'] = new MongoDate( $mongoid->getTimestamp() ); | |
// Save the document | |
$db->$collection->save($doc); | |
} | |
echo "\n\n"; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment