Skip to content

Instantly share code, notes, and snippets.

@grosscorporation
Forked from fkiller/mongodb_searchAll.js
Created December 8, 2017 03:19
Show Gist options
  • Save grosscorporation/3df0cf82b71110c3af2650a0b3079880 to your computer and use it in GitHub Desktop.
Save grosscorporation/3df0cf82b71110c3af2650a0b3079880 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