OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

PyMongo - Import extended json file into MongoDB

  • Thread starter Thread starter Steve
  • Start date Start date
S

Steve

Guest
Is it possible to import an extended JSON file to MongoDB using Python's pymongo?

For instance, the JSON file to import has multiple documents with "$date", for instance:

Code:
[{"t": {"$date": "2024-06-10",...}}, {"t": {"$date": "2024-06-11", ...}}]

At the moment I have the following which is successful, though this reads the import as JSON data and loses the MongoDB type information. Is there anyway of preserving this information, via bson.json_util ?

Code:
from pymongo import MongoClient

client = MongoClient(db_connection)
with open(input_file, 'r') as file:
    data = json.load(file)
    # If JSON contains multiple documents, insert_many is used
    # otherwise insert_one is used for a single document
    if isinstance(data, list):
        client[db_name][collection_name].insert_many(data)
    else:
        client[db_name][collection_name].insert_one(data)

Thanks
<p>Is it possible to import an extended JSON file to MongoDB using Python's pymongo?</p>
<p>For instance, the JSON file to import has multiple documents with "$date", for instance:</p>
<pre><code>[{"t": {"$date": "2024-06-10",...}}, {"t": {"$date": "2024-06-11", ...}}]
</code></pre>
<p>At the moment I have the following which is successful, though this reads the import as JSON data and loses the MongoDB type information. Is there anyway of preserving this information, via bson.json_util ?</p>
<pre><code>from pymongo import MongoClient

client = MongoClient(db_connection)
with open(input_file, 'r') as file:
data = json.load(file)
# If JSON contains multiple documents, insert_many is used
# otherwise insert_one is used for a single document
if isinstance(data, list):
client[db_name][collection_name].insert_many(data)
else:
client[db_name][collection_name].insert_one(data)
</code></pre>
<p>Thanks</p>
 

Online statistics

Members online
0
Guests online
3
Total visitors
3
Top