Skip to content

Instantly share code, notes, and snippets.

@junzis
Last active April 20, 2016 13:43
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 junzis/0ace97b8d709efaa48d1 to your computer and use it in GitHub Desktop.
Save junzis/0ace97b8d709efaa48d1 to your computer and use it in GitHub Desktop.
# a set of useful scripts for mongodb
- batch deleting collections
- extract subset using fast aggregation method
- export query to csv (quick and dirty)
var collectionNames = db.getCollectionNames();
for(var i = 0, len = collectionNames.length; i < len ; i++){
var collectionName = collectionNames[i];
if(collectionName.indexOf('NAMESTARTS_') == 0){
db[collectionName].drop()
}
}
mongodump --db database_name --collection collection_name --out - | gzip > dump_file_name.gz
mongoexport -d DB -c COLL --type=csv --out file_name.csv --fields f1,f2,f3
db.getCollection('FULL_SET').aggregate([{ $match:{ FIELD:"VALUE"} }, { $out: "SUB_SET" }]);
db.collection.find().limit(1).sort({$natural:-1})
db.COLLECTION_NAME.mapReduce(
function(){
var lat = Math.floor(this["loc"]["lat"]);
var lon = Math.floor(this["loc"]["lng"]);
var key = lat + "_" + lon;
emit(key, {count: 1})
},
function(state, values){
var result = {count: 0};
values.forEach(function(value) {
result.count += value.count;
});
return result;
},
{out: "histogram"}
);
use admin
db.runCommand({renameCollection:"sourcedb.mycol",to:"targetdb.mycol"})
mongoexport -d DBNAME -c COLLNAME --query "{'FIELD':'VLAUE'}" --type=csv --fields F1,F2,F3 --out out.csv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment