Skip to content

Instantly share code, notes, and snippets.

@xergiodf
Created December 14, 2018 15:57
Show Gist options
  • Save xergiodf/66a030cf791b790f9e9bddd0f286f0e7 to your computer and use it in GitHub Desktop.
Save xergiodf/66a030cf791b790f9e9bddd0f286f0e7 to your computer and use it in GitHub Desktop.
Mongoose find duplicates by field
const { User } = require("src/db");
/**
* Find all duplicates emails in the User
* mongoose model (mapping users collection)
*
*
* This aggregation function will groups the
* documents comparing emaiils, sanitized
* to lowercase; it adds the "_id" fields to
* a set; and creates a count for the # of
* emails.
*
* After the first group, it matches the results
* filtering only the results with count > 1
*
* At the end of the function, it returns an
* Array of "_id"s
*/
const { User } = require("src/db");
const findDuplicatedEmailsIds = () => {
new Promise((resolve, reject) =>
User.aggregate([
{
$group: {
_id: { email: { $toLower: "$email" } },
ids: { $addToSet: "$_id" },
count: { $sum: 1 }
}
},
{
$match: {
count: { $gt: 1 }
}
}
])
).exec((err, res) => {
if (err) reject(err);
const ids = [];
res.forEach(r => {
r.ids.shift();
r.ids.forEach(id => ids.push(id));
});
});
};
module.exports = findDuplicates;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment