Skip to content

Instantly share code, notes, and snippets.

@chrisckchang
Last active February 16, 2017 15:11
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save chrisckchang/9218534 to your computer and use it in GitHub Desktop.
Save chrisckchang/9218534 to your computer and use it in GitHub Desktop.
Aggregation query to find duplicate key values
// Desired unique index:
// db.collection.ensureIndex({ firstField: 1, secondField: 1 }, { unique: true})
db.collection.aggregate([
{ $group: {
_id: { firstField: "$firstField", secondField: "$secondField" },
uniqueIds: { $addToSet: "$_id" },
count: { $sum: 1 }
}},
{ $match: {
count: { $gt: 1 }
}}
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment