Skip to content

Instantly share code, notes, and snippets.

@IvanaGyro
Created June 22, 2020 09:54
Show Gist options
  • Save IvanaGyro/bbe413aec8b39b24c0e34bc4b64b7bdc to your computer and use it in GitHub Desktop.
Save IvanaGyro/bbe413aec8b39b24c0e34bc4b64b7bdc to your computer and use it in GitHub Desktop.
Helper for exploring MongoDB's schema.
function signature(e){switch(typeof e){case"string":return"s";case"number":return Number.isInteger(e)?"i":"f";case"undefined":return"u";default:return null===e?"n":e.constructor===Array?"a":`{${Object.keys(e).sort().map(r=>`${r}:${signature(e[r])}`).join(",")}}`}}
function deserilize(sign){return eval(`i='i';s='s';n='n';a='a';f='f';var o=${sign};o;`)}
function _diff([e,t]){return Object.keys(e).forEach(f=>{"object"==typeof e[f]&&"object"==typeof t[f]?([e[f],t[f]]=_diff([e[f],t[f]]),Object.keys(e[f]).length||Object.keys(t[f]).length||(delete e[f],delete t[f])):e[f]===t[f]&&(delete e[f],delete t[f])}),[e,t]}
function diff(f,i){return _diff([f,i].map(deserilize))}
// > use mydb
db.mycollection.mapReduce(function() { emit(signature(this), 1)}, function(k, vs) { return Array.sum(vs) }, { out: {replace: 'mycollection_', db: 'mydbschema'}, scope: { signature })
// > use mydbschema
_diff(db.mycollection_.find().sort({value: -1}).toArray().slice(0, 2).map(deserilize))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment