Skip to content

Instantly share code, notes, and snippets.

@jmikola
Created January 18, 2013 17:02
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 jmikola/4566112 to your computer and use it in GitHub Desktop.
Save jmikola/4566112 to your computer and use it in GitHub Desktop.
<?php
$mongoClient = new MongoClient('mongodb://localhost');
$collection = $mongoClient->selectCollection('mydb', 'customers');
// Assume $parms exists as an associative array (perhaps from $_POST)
$rp = 'listcustomer';
switch ($rp) {
case 'listcustomers':
$cursor = $collection->find([], ['_id' => 1, 'name' => 1]);
$jsonResult = json_encode(iterator_to_array($cursor));
break;
case 'getcustomer':
$document = $collection->findOne(['_id' => new MongoId($parms['_id'])]);
$jsonResult = json_encode($document);
break;
case 'setcustomer':
if (empty($parms['_id'])) {
$parms['_id'] = new MongoId($parms['_id']);
} else {
// Unset the _id, since save() will create one
unset($parms['_id']);
}
$collection->save($parms);
$jsonResult = json_encode(['_id' => (string) $parms['_id']]);
break;
case "deletecustomer":
$collection->remove(['_id' => new MongoId($parms['_id'])]);
$jsonResult = json_encode(['_id' => (string) $parms['_id']]);
break;
default:
$jsonResult = json_encode(['error' => 'unsupported rp']);
}
echo $jsonResult;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment