Skip to content

Instantly share code, notes, and snippets.

@jmikola
Created Jan 18, 2013
Embed
What would you like to do?
<?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