Skip to content

Instantly share code, notes, and snippets.

@fkiller
Created September 13, 2017 18:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save fkiller/005dc8a07eaa3321110b3e5753dda71b to your computer and use it in GitHub Desktop.
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 is a set of functions to search entire DB by simple keyword. *
* *
* Developered by Won Dong(fkiller@gmail.com) *
* *
* * 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