Python MongoDB – Useful Resources ”; Previous Next The following resources contain additional information on Python MongoDB. Please use them to get more in-depth knowledge on this. Useful Video Courses Python Flask and SQLAlchemy ORM 22 Lectures 1.5 hours Jack Chan More Detail Python and Elixir Programming Bundle Course 81 Lectures 9.5 hours Pranjal Srivastava More Detail TKinter Course – Build Python GUI Apps 49 Lectures 4 hours John Elder More Detail A Beginner”s Guide to Python and Data Science 81 Lectures 8.5 hours Datai Team Academy More Detail Deploy Face Recognition Project With Python, Django, And Machine Learning Best Seller 93 Lectures 6.5 hours Srikanth Guskra More Detail Professional Python Web Development with Flask 80 Lectures 12 hours Stone River ELearning More Detail Print Page Previous Next Advertisements ”;
Category: python Mongodb
Python MongoDB – Create Collection ”; Previous Next A collection in MongoDB holds a set of documents, it is analogous to a table in relational databases. You can create a collection using the createCollection() method. This method accepts a String value representing the name of the collection to be created and an options (optional) parameter. Using this you can specify the following − The size of the collection. The max number of documents allowed in the capped collection. Whether the collection we create should be capped collection (fixed size collection). Whether the collection we create should be auto-indexed. Syntax Following is the syntax to create a collection in MongoDB. db.createCollection(“CollectionName”) Example Following method creates a collection named ExampleCollection. > use mydb switched to db mydb > db.createCollection(“ExampleCollection”) { “ok” : 1 } > Similarly, following is a query that creates a collection using the options of the createCollection() method. >db.createCollection(“mycol”, { capped : true, autoIndexId : true, size : 6142800, max : 10000 } ) { “ok” : 1 } > Creating a Collection Using Python Following python example connects to a database in MongoDB (mydb) and, creates a collection in it. Example from pymongo import MongoClient #Creating a pymongo client client = MongoClient(”localhost”, 27017) #Getting the database instance db = client[”mydb”] #Creating a collection collection = db[”example”] print(“Collection created……..”) Output Collection created…….. Print Page Previous Next Advertisements ”;
Python MongoDB – Introduction ”; Previous Next Pymongo is a python distribution which provides tools to work with MongoDB, it is the most preferred way to communicate with MongoDB database from python. Installation To install pymongo first of all make sure you have installed python3 (along with PIP) and MongoDB properly. Then execute the following command. C:WINDOWSsystem32>pip install pymongo Collecting pymongo Using cached https://files.pythonhosted.org/packages/cb/a6/b0ae3781b0ad75825e00e29dc5489b53512625e02328d73556e1ecdf12f8/pymongo-3.9.0-cp37-cp37m-win32.whl Installing collected packages: pymongo Successfully installed pymongo-3.9.0 Verification Once you have installed pymongo, open a new text document, paste the following line in it and, save it as test.py. import pymongo If you have installed pymongo properly, if you execute the test.py as shown below, you should not get any issues. D:Python_MongoDB>test.py D:Python_MongoDB> Print Page Previous Next Advertisements ”;
Python MongoDB – Create Database ”; Previous Next Unlike other databases, MongoDB does not provide separate command to create a database. In general, the use command is used to select/switch to the specific database. This command initially verifies whether the database we specify exists, if so, it connects to it. If the database, we specify with the use command doesn’t exist a new database will be created. Therefore, you can create a database in MongoDB using the Use command. Syntax Basic syntax of use DATABASE statement is as follows − use DATABASE_NAME Example Following command creates a database named in mydb. >use mydb switched to db mydb You can verify your creation by using the db command, this displays the current database. >db mydb Creating Database Using Python To connect to MongoDB using pymongo, you need to import and create a MongoClient, then you can directly access the database you need to create in attribute passion. Example Following example creates a database in MangoDB. from pymongo import MongoClient #Creating a pymongo client client = MongoClient(”localhost”, 27017) #Getting the database instance db = client[”mydb”] print(“Database created……..”) #Verification print(“List of databases after creating new one”) print(client.list_database_names()) Output Database created…….. List of databases after creating new one: [”admin”, ”config”, ”local”, ”mydb”] You can also specify the port and host names while creating a MongoClient and can access the databases in dictionary style. Example from pymongo import MongoClient #Creating a pymongo client client = MongoClient(”localhost”, 27017) #Getting the database instance db = client[”mydb”] print(“Database created……..”) Output Database created…….. Print Page Previous Next Advertisements ”;
Python MongoDB – Drop Collection ”; Previous Next You can delete collections using drop() method of MongoDB. Syntax Following is the syntax of drop() method − db.COLLECTION_NAME.drop() Example Following example drops collection with name sample − > show collections myColl sample > db.sample.drop() true > show collections myColl Dropping Collection Using Python You can drop/delete a collection from the current by invoking drop() method. Example from pymongo import MongoClient #Creating a pymongo client client = MongoClient(”localhost”, 27017) #Getting the database instance db = client[”example2”] #Creating a collection col1 = db[”collection”] col1.insert_one({“name”: “Ram”, “age”: “26”, “city”: “Hyderabad”}) col2 = db[”coll”] col2.insert_one({“name”: “Rahim”, “age”: “27”, “city”: “Bangalore”}) col3 = db[”myColl”] col3.insert_one({“name”: “Robert”, “age”: “28”, “city”: “Mumbai”}) col4 = db[”data”] col4.insert_one({“name”: “Romeo”, “age”: “25”, “city”: “Pune”}) #List of collections print(“List of collections:”) collections = db.list_collection_names() for coll in collections: print(coll) #Dropping a collection col1.drop() col4.drop() print(“List of collections after dropping two of them: “) #List of collections collections = db.list_collection_names() for coll in collections: print(coll) Output List of collections: coll data collection myColl List of collections after dropping two of them: coll myColl Print Page Previous Next Advertisements ”;
Python MongoDB – Query
Python MongoDB – Query ”; Previous Next While retrieving using find() method, you can filter the documents using the query object. You can pass the query specifying the condition for the required documents as a parameter to this method. Operators Following is the list of operators used in the queries in MongoDB. Operation Syntax Example Equality {“key” : “value”} db.mycol.find({“by”:”tutorials point”}) Less Than {“key” :{$lt:”value”}} db.mycol.find({“likes”:{$lt:50}}) Less Than Equals {“key” :{$lte:”value”}} db.mycol.find({“likes”:{$lte:50}}) Greater Than {“key” :{$gt:”value”}} db.mycol.find({“likes”:{$gt:50}}) Greater Than Equals {“key” {$gte:”value”}} db.mycol.find({“likes”:{$gte:50}}) Not Equals {“key”:{$ne: “value”}} db.mycol.find({“likes”:{$ne:50}}) Example1 Following example retrieves the document in a collection whose name is sarmista. from pymongo import MongoClient #Creating a pymongo client client = MongoClient(”localhost”, 27017) #Getting the database instance db = client[”sdsegf”] #Creating a collection coll = db[”example”] #Inserting document into a collection data = [ {“_id”: “1001”, “name”: “Ram”, “age”: “26”, “city”: “Hyderabad”}, {“_id”: “1002”, “name”: “Rahim”, “age”: “27”, “city”: “Bangalore”}, {“_id”: “1003”, “name”: “Robert”, “age”: “28”, “city”: “Mumbai”}, {“_id”: “1004”, “name”: “Romeo”, “age”: “25”, “city”: “Pune”}, {“_id”: “1005”, “name”: “Sarmista”, “age”: “23”, “city”: “Delhi”}, {“_id”: “1006”, “name”: “Rasajna”, “age”: “26”, “city”: “Chennai”} ] res = coll.insert_many(data) print(“Data inserted ……”) #Retrieving data print(“Documents in the collection: “) for doc1 in coll.find({“name”:”Sarmista”}): print(doc1) Output Data inserted …… Documents in the collection: {”_id”: ”1005”, ”name”: ”Sarmista”, ”age”: ”23”, ”city”: ”Delhi”} Example2 Following example retrieves the document in a collection whose age value is greater than 26. from pymongo import MongoClient #Creating a pymongo client client = MongoClient(”localhost”, 27017) #Getting the database instance db = client[”ghhj”] #Creating a collection coll = db[”example”] #Inserting document into a collection data = [ {“_id”: “1001”, “name”: “Ram”, “age”: “26”, “city”: “Hyderabad”}, {“_id”: “1002”, “name”: “Rahim”, “age”: “27”, “city”: “Bangalore”}, {“_id”: “1003”, “name”: “Robert”, “age”: “28”, “city”: “Mumbai”}, {“_id”: “1004”, “name”: “Romeo”, “age”: “25”, “city”: “Pune”}, {“_id”: “1005”, “name”: “Sarmista”, “age”: “23”, “city”: “Delhi”}, {“_id”: “1006”, “name”: “Rasajna”, “age”: “26”, “city”: “Chennai”} ] res = coll.insert_many(data) print(“Data inserted ……”) #Retrieving data print(“Documents in the collection: “) for doc in coll.find({“age”:{“$gt”:”26″}}): print(doc) Output Data inserted …… Documents in the collection: {”_id”: ”1002”, ”name”: ”Rahim”, ”age”: ”27”, ”city”: ”Bangalore”} {”_id”: ”1003”, ”name”: ”Robert”, ”age”: ”28”, ”city”: ”Mumbai”} Print Page Previous Next Advertisements ”;
Python MongoDB – Home
Python MongoDB Tutorial PDF Version Quick Guide Resources Job Search Discussion Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985-1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). This tutorial gives enough understanding on Python programming language. This tutorial explains how to communicate with MongoDB database in detail, along with examples. Audience This tutorial is designed for python programmers who would like to understand the pymongo modules in detail. Prerequisites Before proceeding with this tutorial, you should have a good understanding of python programming language. It is also recommended to have basic understanding of the databases – MongoDB. Print Page Previous Next Advertisements ”;
Python MongoDB – Insert Document ”; Previous Next You can store documents into MongoDB using the insert() method. This method accepts a JSON document as a parameter. Syntax Following is the syntax of the insert method. >db.COLLECTION_NAME.insert(DOCUMENT_NAME) Example > use mydb switched to db mydb > db.createCollection(“sample”) { “ok” : 1 } > doc1 = {“name”: “Ram”, “age”: “26”, “city”: “Hyderabad”} { “name” : “Ram”, “age” : “26”, “city” : “Hyderabad” } > db.sample.insert(doc1) WriteResult({ “nInserted” : 1 }) > Similarly, you can also insert multiple documents using the insert() method. > use testDB switched to db testDB > db.createCollection(“sample”) { “ok” : 1 } > data = [ {“_id”: “1001”, “name”: “Ram”, “age”: “26”, “city”: “Hyderabad”}, {“_id”: “1002”, “name” : “Rahim”, “age” : 27, “city” : “Bangalore” }, {“_id”: “1003”, “name” : “Robert”, “age” : 28, “city” : “Mumbai” } ] [ {“_id” : “1001”, “name” : “Ram”, “age” : “26”, “city” : “Hyderabad”}, {“_id” : “1002”, “name” : “Rahim”, “age” : 27, “city” : “Bangalore”}, {“_id” : “1003”, “name” : “Robert”, “age” : 28, “city” : “Mumbai”} ] > db.sample.insert(data) BulkWriteResult({ “writeErrors” : [ ], “writeConcernErrors” : [ ], “nInserted” : 3, “nUpserted” : 0, “nMatched” : 0, “nModified” : 0, “nRemoved” : 0, “upserted” : [ ] }) > Creating a Collection Using Python Pymongo provides a method named insert_one() to insert a document in MangoDB. To this method, we need to pass the document in dictionary format. Example Following example inserts a document in the collection named example. from pymongo import MongoClient #Creating a pymongo client client = MongoClient(”localhost”, 27017) #Getting the database instance db = client[”mydb”] #Creating a collection coll = db[”example”] #Inserting document into a collection doc1 = {“name”: “Ram”, “age”: “26”, “city”: “Hyderabad”} coll.insert_one(doc1) print(coll.find_one()) Output {”_id”: ObjectId(”5d63ad6ce043e2a93885858b”), ”name”: ”Ram”, ”age”: ”26”, ”city”: ”Hyderabad”} To insert multiple documents into MongoDB using pymongo, you need to invoke the insert_many() method. from pymongo import MongoClient #Creating a pymongo client client = MongoClient(”localhost”, 27017) #Getting the database instance db = client[”mydb”] #Creating a collection coll = db[”example”] #Inserting document into a collection data = [ {“_id”: “101”, “name”: “Ram”, “age”: “26”, “city”: “Hyderabad”}, {“_id”: “102”, “name”: “Rahim”, “age”: “27”, “city”: “Bangalore”}, {“_id”: “103”, “name”: “Robert”, “age”: “28”, “city”: “Mumbai”} ] res = coll.insert_many(data) print(“Data inserted ……”) print(res.inserted_ids) Output Data inserted …… [”101”, ”102”, ”103”] Print Page Previous Next Advertisements ”;
Python MongoDB – Limit
Python MongoDB – Limit ”; Previous Next While retrieving the contents of a collection you can limit the number of documents in the result using the limit() method. This method accepts a number value representing the number of documents you want in the result. Syntax Following is the syntax of the limit() method − >db.COLLECTION_NAME.find().limit(NUMBER) Example Assume we have created a collection and inserted 5 documents into it as shown below − > use testDB switched to db testDB > db.createCollection(“sample”) { “ok” : 1 } > data = [ … {“_id”: “1001”, “name”: “Ram”, “age”: “26”, “city”: “Hyderabad”}, … {“_id”: “1002”, “name”: “Rahim”, “age”: 27, “city”: “Bangalore”}, … {“_id”: “1003”, “name”: “Robert”, “age”: 28, “city”: “Mumbai”}, … {“_id”: “1004”, “name”: “Romeo”, “age”: 25, “city”: “Pune”}, … {“_id”: “1005”, “name”: “Sarmista”, “age”: 23, “city”: “Delhi”}, … {“_id”: “1006”, “name”: “Rasajna”, “age”: 26, “city”: “Chennai”} ] > db.sample.insert(data) BulkWriteResult({ “writeErrors” : [ ], “writeConcernErrors” : [ ], “nInserted” : 6, “nUpserted” : 0, “nMatched” : 0, “nModified” : 0, “nRemoved” : 0, “upserted” : [ ] }) Following line retrieves the first 3 documents of the collection. > db.sample.find().limit(3) { “_id” : “1001”, “name” : “Ram”, “age” : “26”, “city” : “Hyderabad” } { “_id” : “1002”, “name” : “Rahim”, “age” : 27, “city” : “Bangalore” } { “_id” : “1003”, “name” : “Robert”, “age” : 28, “city” : “Mumbai” } Limiting the Documents Using Python To restrict the results of a query to a particular number of documents pymongo provides the limit() method. To this method pass a number value representing the number of documents you need in the result. Example Following example retrieves first three documents in a collection. from pymongo import MongoClient #Creating a pymongo client client = MongoClient(”localhost”, 27017) #Getting the database instance db = client[”l”] #Creating a collection coll = db[”myColl”] #Inserting document into a collection data = [ {“_id”: “1001”, “name”: “Ram”, “age”: “26”, “city”: “Hyderabad”}, {“_id”: “1002”, “name”: “Rahim”, “age”: “27”, “city”: “Bangalore”}, {“_id”: “1003”, “name”: “Robert”, “age”: “28”, “city”: “Mumbai”}, {“_id”: “1004”, “name”: “Romeo”, “age”: 25, “city”: “Pune”}, {“_id”: “1005”, “name”: “Sarmista”, “age”: 23, “city”: “Delhi”}, {“_id”: “1006”, “name”: “Rasajna”, “age”: 26, “city”: “Chennai”} ] res = coll.insert_many(data) print(“Data inserted ……”) #Retrieving first 3 documents using the find() and limit() methods print(“First 3 documents in the collection: “) for doc1 in coll.find().limit(3): print(doc1) Output Data inserted …… First 3 documents in the collection: {”_id”: ”1001”, ”name”: ”Ram”, ”age”: ”26”, ”city”: ”Hyderabad”} {”_id”: ”1002”, ”name”: ”Rahim”, ”age”: ”27”, ”city”: ”Bangalore”} {”_id”: ”1003”, ”name”: ”Robert”, ”age”: ”28”, ”city”: ”Mumbai”} Print Page Previous Next Advertisements ”;
Python MongoDB – Discussion
Discuss Python MongoDB ”; Previous Next Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985-1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). This tutorial gives enough understanding on Python programming language. This tutorial explains how to communicate with MongoDB database in detail, along with examples. Print Page Previous Next Advertisements ”;