Skip to content

Instantly share code, notes, and snippets.

@spacemonkey
Created July 4, 2013 10:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spacemonkey/5926512 to your computer and use it in GitHub Desktop.
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…
<?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