Skip to content

Instantly share code, notes, and snippets.

@cjthompson
Last active September 28, 2021 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjthompson/01b46382e8fd3a6d613e829418ddd986 to your computer and use it in GitHub Desktop.
Save cjthompson/01b46382e8fd3a6d613e829418ddd986 to your computer and use it in GitHub Desktop.
Find all possible fields and their types from a MongoDB collection
var obj = {};
function reduce(accum, doc) {
for (var key in doc) {
if (doc.hasOwnProperty(key) && typeof doc[key] !== 'function') {
const type = typeof doc[key]
if (type === 'object') {
const aKey = (accum[key] && typeof accum[key] === 'string') ? key + '_obj' : key
accum[aKey] = accum[aKey] ? accum[aKey] : {}
reduce(accum[aKey], doc[key])
} else {
if (!accum[key]) {
accum[key] = type
} else if (typeof accum[key] === 'string' && accum[key].indexOf(type) === -1) {
accum[key] = obj[key] + ',' + type
}
}
}
}
}
db.myCollection.find({}).limit(100000).forEach(doc => reduce(obj, doc));
obj;
[
{
"_id": {
},
"Account": "string",
"Amount": "string",
"Destination": "string",
"Fee": "string",
"Flags": "number",
"TransactionType": "string",
"amount": "string,number",
"amount_obj": {
"value": "number"
},
"attachment": {
},
"balance": "string",
"balance_obj": {
"value": "number",
"USD": "number",
"EURO": {
"value": "number"
}
},
"brokerFees": {
"0": {
"value": "number"
},
"1": "number",
"1_obj": {
"value": "number"
}
},
"confirmations": "number,string",
"date": {
"value": "number"
},
"details": {
"address": "string",
"amount": "number",
"category": "string",
"amount_obj": {
"value": "number"
}
},
"fee": "number",
"fee_obj": {
"value": "number",
"amount": {
"value": "number"
},
"asset_id": {
"value": "number"
}
},
"ledger_entries": {
"0": {
"from_account": "string",
"to_account": "string",
"amount": {
"amount": {
"value": "number"
},
"asset": "number"
},
"memo": "string",
"running_balances": {
"0": {
"0": "string",
"1": {
"0": {
"0": {
"value": "number"
},
"1": {
"amount": {
"value": "number"
},
"asset": {
"value": "number"
}
}
},
"1": {
"0": {
"value": "number"
},
"1": {
"amount": {
"value": "number"
},
"asset_id": {
"value": "number"
}
}
}
}
}
}
}
},
"pending": {
"_id": {},
"withdrawalAmount": "string",
"status": "string",
"uuid": "string"
},
"result": "string",
"result_obj": {
"0": {
"amount": "string",
"date": "string",
"rate": "string",
"total": "string",
"tradeID": "string",
"type": "string"
},
"1": {
"amount": "string",
"date": "string",
"rate": "string",
"total": "string",
"tradeID": "string",
"type": "string"
}
}
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment