I usually use this little script to extract a CSV file with the contents of a MongoDB collection. Now, for this to make sense, the collection should have similar documents, otherwise, the exported data won't make much sense.
The script iterates through the document keys and prints a CSV with the content. It's only suitable if the collection is somewhat manageable.
// Version 3.0 (01-02-2020)
let datos = []
const scanRecursive = (prefix, element) => {
let object_keys = []
if (!element) return object_keys
Object.keys(element).forEach(key=> {
if (typeof element[key] !== "object") object_keys.push(prefix + key)
else scanRecursive(prefix + key + ".", element[key]).forEach(i_key=> object_keys.push(i_key))
})
return object_keys
}
const getValue = (key, object) => {
const path = key.split(".")
let current_object = object
for (let i=0; i<path.length; i++) {
if (current_object && current_object[path[i]]) current_object = current_object[path[i]])
else return undefined
}
if (typeof current_object === "string") {
return current_object
.replace(/(\r\n|\n|\r)/gm, "")
.replace(/;/g, "")
}
return current_object
}
db.<collection-name>.find({}).forEach(el=> {
const keys = scanRecursive("", el)
keys.forEach(key=> !datos.includes(key) && datos.push(key))
})
print(datos.sort().join(";"))
db.<collection-name>.find({}).forEach(el=> print(datos.map(key=> getValue(key, el)).join(";")))
Make sure to substitute <collection-name> with the collection name that you want to export to CSV.