Skip to content

Instantly share code, notes, and snippets.

@KEIII
Last active November 12, 2016 10:39
Show Gist options
  • Save KEIII/b481a74dc625deb36e474819fbef0284 to your computer and use it in GitHub Desktop.
Save KEIII/b481a74dc625deb36e474819fbef0284 to your computer and use it in GitHub Desktop.
MongoDB JavaScript function that will return an array of all records matching specified criteria, searching across all collections in the current database. Original from https://stackoverflow.com/a/32790853/1847657
/**
* Find into all collections.
*
* @param {{}} query
* @param {[]} fields
* @param {{}} sort
*
* @return {Array}
*/
function findAll(query, fields, sort) {
var result = [];
var collectionNames = db.getCollectionNames();
collectionNames.forEach(function (collectionName) {
if (collectionName === 'system.indexes') {
return;
}
db[collectionName]
.find(query || {}, fields || [])
.sort(sort || {})
.forEach(function (doc) {
result.push(doc);
})
;
});
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment