def _write_pretty(file_path, documents): serialized = [] for doc in documents.values(): serialized.append( _dumps(BSON(doc).decode(), json_options=CANONICAL_JSON_OPTIONS)) with open(file_path, "w") as fp: fp.write("[\n{}\n]".format(",\n".join(serialized)))
def monty_dump(file_path, documents, json_options=None): if not isinstance(documents, list): raise TypeError("Param `documents` should be a list.") opt = json_options if json_options else _default_json_opts serialized = [_dumps(doc, json_options=opt) for doc in documents] if not os.path.isdir(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) with open(file_path, "w") as fp: fp.write("\n".join(serialized))
def montyexport(database, collection, out, fileds=None, query=None, json_options=None): """Produces a JSON export of data stored in a MontyCollection instance Example: >>> from montydb import open_repo, utils >>> with open_repo("foo/bar"): >>> utils.montyexport("db", "col", "/data/dump.json") >>> Args: database (str): Database name collection (str): Collection name to export from out (str): Output file path fields (str, list): Specifies a field name string or a list fields to include in the export. query (dict): Provides a query document to return matching documents in the export. json_options (JSONOptions): A JSONOptions instance used to modify the decoding of MongoDB Extended JSON types. Default None. """ collection = _collection(database, collection) opt = json_options or _default_json_opts fileds = fileds or [] out = os.path.abspath(out) if not os.path.isdir(os.path.dirname(out)): os.makedirs(os.path.dirname(out)) if isinstance(fileds, string_type): fileds = [fileds] projection = {field: True for field in fileds} or None with open(out, "w") as fp: for doc in collection.find(query, projection=projection): serialized = _dumps(doc, json_options=opt) fp.write(serialized + "\n")
def json_dumps(cls, doc, json_options=None): from bson.json_util import dumps as _dumps json_options = json_options or cls.CANONICAL_JSON_OPTIONS return _dumps(doc, json_options=json_options)