Skip to content

Instantly share code, notes, and snippets.

@b3rew
Last active July 14, 2017 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save b3rew/ba6670f1c45c83cdeb22acb4c596b041 to your computer and use it in GitHub Desktop.
Save b3rew/ba6670f1c45c83cdeb22acb4c596b041 to your computer and use it in GitHub Desktop.
MongoDB query cheetsheet
//update test collection
db.test.update({foo: "bar"}, {$set: {test: "success!"}}, {multi: true})
//Find duplicate records by key_name in MongoDB
db.collection.aggregate(
{"$group" : { "_id": "$key_name", "count": { "$sum": 1 } } },
{"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } },
{"$project": {"key_name" : "$_id", "_id" : 0} }
)
//remove duplicate documnets by key_name (Index your key_name before running this to increase speed)
db.collection.find({}, {key_name:1}).sort({_id:1}).forEach(function(doc){
db.collection.remove({_id:{$gt:doc._id}, key_name:doc.key_name});
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment