MongoDB database interface syntax

I'm trying to program something that can import a ton of data from Excel and insert it into a MongoDB Atlas database.
I'm a relatively proficient programmer but completely new to Python and MongoDB so please excuse me for asking stupid questions.

I can get the data in form Excel but need a little guidance on the principles of how to write code that will put data into MongoDB. I use the professional version of PyCharm and have managed to setup a functioning database connection to my MongoDB and can make queries in the console but I can't get my head around how to access the DB from code in a .py file

Any guidance will be very much appreciated :-)

评论操作 固定链接

You can do it directly from the init.py's main function like this (taken from a tutorial here):

Contents of init.py:

import pymongo

def main():
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["menagerie"]
mycol = mydb["people"]

mydict = { "name": "Jane", "address": "Highway 38" }

x = mycol.insert_one(mydict)

if __name__ == "__main__":
main()

Or you can write the code in a separate .py file, then just import it as a module to any file with an executable function and call it from that function. See my example below (taken from this tutorial):

  • Contents of mongodb.py:
# Python code to illustrate inserting data in MongoDB
from pymongo import MongoClient

try:
conn = MongoClient()
print("Connected successfully!!!")
except:
print("Could not connect to MongoDB")

# database
db = conn.menagerie

# Created or Switched to collection names: my_gfg_collection
collection = db.people

emp_rec1 = {
"name":"Mr.Geek",
"eid":24,
"location":"delhi"
}
emp_rec2 = {
"name":"Mr.Shaurya",
"eid":14,
"location":"delhi"
}

# Insert Data
rec_id1 = collection.insert_one(emp_rec1)
rec_id2 = collection.insert_one(emp_rec2)

print("Data inserted with record ids",rec_id1," ",rec_id2)

# Printing the data inserted
cursor = collection.find()
for record in cursor:
print(record)
  • Contents of init.py:
import mongodb

if __name__ == "__main__":
mongodb
In the IDE, you just need to press the green 'Run' button in the editor next to the executable function.
Note that the output will be printed to console only if you add the corresponding "print" statements to the code.
0

请先登录再写评论。