Skip to content

Instantly share code, notes, and snippets.

@GeertHauwaerts
Created November 29, 2018 22:05
Show Gist options
  • Save GeertHauwaerts/5bd6d3310e801bb7d8c4bf66cce099ed to your computer and use it in GitHub Desktop.
Save GeertHauwaerts/5bd6d3310e801bb7d8c4bf66cce099ed to your computer and use it in GitHub Desktop.
PHP - MonogoDB - Remove duplicates
<?php
/**
* This example assumes:
* _id: entry unique key
* field: a field that is not unique, but you want to remove all
* entries that have the same value while keeping the first entry.
*/
$duplicates = $collection->aggregate([
[
'$group' => [
'_id' => [ 'field' => '$field' ],
'dups' => [ '$addToSet' => '$_id' ],
'count' => [ '$sum' => 1 ]
]
],
[
'$match' => [
'count' => [ '$gt' => 1 ]
]
]
]);
foreach ($duplicates as $duplicate) {
unset($duplicate->dups[0]);
$collection->deleteMany([
'_id' => [ '$in' => $duplicate->dups ]
]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment