Created
September 13, 2017 18:21
-
-
Save fkiller/005dc8a07eaa3321110b3e5753dda71b to your computer and use it in GitHub Desktop.
This is a set of functions to search entire DB by simple keyword. If you need to find something from any records from any collections that you don't remember names, just load this functions and `searchAll('any keyword')` in Mongo console.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/************************************************************************ | |
* This is a set of functions to search entire DB by simple keyword. * | |
* * | |
* Developered by Won Dong([email protected]) * | |
* * | |
* * Usage: searchAll('any keyword') * | |
* * | |
*************************************************************************/ | |
function createOR(fieldNames, keyword) { | |
var query = []; | |
fieldNames.forEach(function (item) { | |
var temp = {}; | |
temp[item] = { $regex: '.*' + keyword + '.*' }; | |
query.push(temp); | |
}); | |
if (query.length == 0) return false; | |
return { $or: query }; | |
} | |
function keys(collectionName) { | |
mr = db.runCommand({ | |
'mapreduce': collectionName, | |
'map': function () { | |
for (var key in this) { emit(key, null); } | |
}, | |
'reduce': function (key, stuff) { return null; }, | |
'out': 'my_collection' + '_keys' | |
}); | |
return db[mr.result].distinct('_id'); | |
} | |
function findany(collection, keyword) { | |
var query = createOR(keys(collection.getName())); | |
if (query) { | |
return collection.findOne(query, keyword); | |
} else { | |
return false; | |
} | |
} | |
function searchAll(keyword) { | |
var all = db.getCollectionNames(); | |
var results = []; | |
all.forEach(function (collectionName) { | |
print(collectionName); | |
if (db[collectionName]) results.push(findany(db[collectionName], keyword)); | |
}); | |
return results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment