Created
November 29, 2018 22:05
-
-
Save GeertHauwaerts/5bd6d3310e801bb7d8c4bf66cce099ed to your computer and use it in GitHub Desktop.
PHP - MonogoDB - Remove duplicates
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 | |
/** | |
* 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