Reputation: 707
I do not have much experience, I looked at many articles, the result did not lead to anything. I have a small collection (85 documents), I need to export it using python. Yes, it was him. If there are no problems with inserting documents, setting indexes, then here they appeared.
As I understand it is necessary to use the method find
.
Here's an example document of a collection.
{"_id":{"$oid":"6012b7e0fe7371258899441e"}, "date":"2021-01-23","confirmed":12638,"deaths":113,"recovered":10710,
"region_name":"Республика Адыгея",
"region_code":"RU-AD","isolation_start":"16.07.2020 21:58:11",
"level":3,"self_isolation":null}
How is it necessary to make transformations in order to get csv? If it doesn't make it difficult, can I have a code example?
Upvotes: 1
Views: 5238
Reputation: 707
Apparently I sat at the monitor. I did two ways, maybe someone will need it.
client = MongoClient('mongodb://localhost:27017/')
db = client.test_import
collection = db.myimport2
csv_columns = ['_id','date','confirmed', 'deaths', 'recovered', 'region_name', 'region_code', 'isolation_start', 'level', 'self_isolation']
with open('mycsvfile.csv', 'w', encoding='utf-8') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
writer.writeheader()
for post in collection.find():
writer.writerow(post)
and pandas
client = MongoClient('mongodb://localhost:27017/')
db = client.test_import
collection = db.myimport2
df = pd.DataFrame(list(collection.find()))
df.to_csv('mycsvfile2.csv')
Upvotes: 2