OH: NodeJS + MongoDB is this generation’s Laurel and Hardy stack (“look at this mess you got me into”). Last generation’s was PHP + MySQL
— Stephan H. Wissel (@notessensei) June 9, 2016
OH: NodeJS + MongoDB is this generation’s Laurel and Hardy stack (“look at this mess you got me into”). Last generation’s was PHP + MySQL
— Stephan H. Wissel (@notessensei) June 9, 2016
The Little MongoDB book by Karl Seguin is free, and is and awesome resource for those new to MongoDB:
The code below demonstrates how to use Python to connect to a MongoDB database. I chose to use a cloud based instance of MongoDB provided free of charge by MongoLab.com. The script demonstrates how to:
I also used a local instance of MongoDB for testing. You will will need to use a Python package manager such as EasyInstall to install the PyMongo library.
Here is the Python code:
# mongo_hello_world.py # Author: Bruce Elgort # Date: March 18, 2014 # Purpose: To demonstrate how to use Python to # 1) Connect to a MongoDB document collection # 2) Insert a document # 3) Display all of the documents in a collection</code> from pymongo import MongoClient # connect to the MongoDB on MongoLab # to learn more about MongoLab visit http://www.mongolab.com # replace the "" in the line below with your MongoLab connection string # you can also use a local MongoDB instance connection = MongoClient("yourmongodbconnectionstring") # connect to the students database and the ctec121 collection db = connection.students.ctec121 # create a dictionary to hold student documents # create dictionary student_record = {} # set flag variable flag = True # loop for data input while (flag): # ask for input student_name,student_grade = input("Enter student name and grade: ").split(',') # place values in dictionary student_record = {'name':student_name,'grade':student_grade} # insert the record db.insert(student_record) # should we continue? flag = input('Enter another record? ') if (flag[0].upper() == 'N'): flag = False # find all documents results = db.find() print() print('+-+-+-+-+-+-+-+-+-+-+-+-+-+-') # display documents from collection for record in results: # print out the document print(record['name'] + ',',record['grade']) print() # close the connection to MongoDB connection.close()
If you have any questions please let me know.
Take free online courses from the creators of MongoDB. MongoDB University offers courses for both developers and DBAs.
More than 100,000 people have enrolled in our courses to date.