Skip to content

Instantly share code, notes, and snippets.

@marinbek
Last active October 12, 2017 16:33
Show Gist options
  • Save marinbek/74a90e108739bf3e03e9f9f3a44d16cc to your computer and use it in GitHub Desktop.
Save marinbek/74a90e108739bf3e03e9f9f3a44d16cc to your computer and use it in GitHub Desktop.
useful mongo scripts

Deleting duplicates

 var count=0;
 var coll = [];
 
 db.getCollection('some_collection').aggregate([
    { "$group": {
        "_id": { "id": "$id" },
        "dups": { "$push": "$_id" },
        "count": { "$sum": 1 }
    }},
    { "$match": { "count": { "$gt": 1 } }}
],
    {"allowDiskUse": true}).map(function(record, index){
        count++;
        coll.push(record.dups[0]);
 }); 
printjson(coll);
 
//  db.getCollection('coins_tweets_stream').remove({_id:{$in:coll}})  

Finding maximum

Faster than aggregate!

db.getCollection('some-collection').find({}).sort({"id":-1}).limit(1)

Create index

db.getCollection('collection').createIndex( { "id": 1 }, { unique: true } )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment