MongoDB
 SQL >> Datenbank >  >> NoSQL >> MongoDB

Mit PyMongo eine MongoDB-Collection nach JSON dumpen

Ein gültiges JSON-Array schreiben

Holen Sie alle Dokumente und serialisieren Sie sie mit bson.json_util.dumps. Bauen Sie die Datei als echtes JSON-Array, um Probleme mit nachlaufenden Kommas zu vermeiden.

from bson.json_util import dumps from pymongo import MongoClient if __name__ == '__main__': client = MongoClient() db = client.db_name collection = db.collection_name cursor = collection.find({}) with open('collection.json', 'w') as file: file.write('[') first = True for document in cursor: if not first: file.write(',') file.write(dumps(document)) first = False file.write(']')

Das erzeugt eine portable JSON-Repräsentation der Collection.