Skip to main content

Posts

Showing posts with the label MongoDB Query

PYTHON MONGODB LIMIT

M ONGODB LIMIT Limit the Result To limit the result in MongoDB, we use the limit() method. The limit() method takes one parameter, a number defining how many documents to return. Limit the result to only return 5 documents: import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] myresult = mycol.find().limit(5) for x in myresult:   print(x) {'_id': ObjectId('6325d5001d9e9d4c027643b8'), 'name': 'Kartik'} {'_id': ObjectId('6325e1ef7e4337dbd6d8b9a1'), 'name': 'Kartik'} {'_id': ObjectId('6325e20d0bea1e2841fcdd06'), 'name': 'Kartik'} {'_id': ObjectId('6325e2381039de66af625c07'), 'name': 'Kartik'} {'_id': ObjectId('6325e26da4ef8259d33e1a33'), 'name': 'Kartik'}

PYTHON UPDATE COLLECTION

U PDATE COLLECTION Update Collection You can update a record, or document as it is called in MongoDB, by using the update_one() method. The first parameter of the update_one() method is a query object defining which document to update. Note: If the query finds more than one record, only the first occurrence is updated. The second parameter is an object defining the new values of the document. Change the address from "Valley" to "Canyon": import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] myquery = { "address": "Valley 345" } newvalues = { "$set": { "address": "Canyon 123" } } mycol.update_one(myquery, newvalues) #print "customers" after the update: for x in mycol.find():   print(x) Update Many To update all documents that meets the criteria of the query, use the update_

PYTHON MONGODB DROP COLLECTION

M ONGODB DROP COLLECTION Delete Collection You can delete a table, or collection as it is called in MongoDB, by using the drop() method. Delete the "customers" collection: import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] mycol.drop() The drop() method returns true if the collection was dropped successfully, and false if the collection does not exist.

PYTHON MONGODB DELETE

M ONGODB DELETE Delete Document To delete one document, we use the delete_one() method. The first parameter of the delete_one() method is a query object defining which document to delete. Note: If the query finds more than one document, only the first occurrence is deleted. Delete the document with the address "Mountain 21": import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] myquery = { "address": "Mountain 21" } mycol.delete_one(myquery) Delete Many Documents To delete more than one document, use the delete_many() method. The first parameter of the delete_many() method is a query object defining which documents to delete. Delete all documents were the address starts with the letter S: import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol =

PYTHON MONGODB SORT

M ONGODB SORT Sort the Result Use the sort() method to sort the result in ascending or descending order. The sort() method takes one parameter for "fieldname" and one parameter for "direction" (ascending is the default direction). Sort the result alphabetically by name: import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] mydoc = mycol.find().sort("name") for x in mydoc:   print(x) Sort Descending Use the value -1 as the second parameter to sort descending. sort("name", 1) #ascending sort("name", -1) #descending Sort the result reverse alphabetically by name: import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] mydoc = mycol.find().sort("name", -1) for x in mydoc:   print(x)

PYTHON MONGODB QUERY

M ONGODB QUERY Filter the Result When finding documents in a collection, you can filter the result by using a query object. The first argument of the find() method is a query object, and is used to limit the search. import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] for x in mycol.find({"address": "California"},{ "_id": 0 }):   print(x) {'name': 'Kartik', 'address': 'California'} Advanced Query To make advanced queries you can use modifiers as values in the query object. E.g. to find the documents where the "address" field starts with the letter "S" or higher (alphabetically), use the greater than modifier: {"$gt": "S"}: Find documents where the address starts with the letter "S" or higher: import pymongo myclient = pymongo.MongoClient(&

PYTHON MONGODB FIND

M ONGODB FIND In MongoDB we use the find() and find_one() methods to find data in a collection. Just like the SELECT statement is used to find data in a table in a MySQL database. Find One To select data from a collection in MongoDB, we can use the find_one() method. The find_one() method returns the first occurrence in the selection. Find the first document in the customers collection: import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] x = mycol.find_one() print(x) Find All To select data from a table in MongoDB, we can also use the find() method. The find() method returns all occurrences in the selection. The first parameter of the find() method is a query object. In this example we use an empty query object, which selects all documents in the collection. No parameters in the find() method gives you the same result as SELECT * in MySQL. Return all

PYTHON MONGODB INESRT

M ONGODB INESRT Insert Into Collection A document in MongoDB is the same as a record in SQL databases. To insert a record, or document as it is called in MongoDB, into a collection, we use the insert_one() method. The first parameter of the insert_one() method is a dictionary containing the name(s) and value(s) of each field in the document you want to insert. Insert a record in the "customers" collection: import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] mydict = { "name": "John", "address": "Highway 37" } x = mycol.insert_one(mydict) #The insert_one() method returns a InsertOneResult object print(x.inserted_id) #inserted_id, that holds the id of the inserted document. Insert Multiple Documents To insert multiple documents into a collection in MongoDB, we use the insert_many() method. The first param

PYTHON MONGODB CREATE DATABASE & COLLECTION

M ONGODB CREATE DATABASE & COLLECTION Creating a Database To create a database in MongoDB, start by creating a MongoClient object, then specify a connection URL with the correct ip address and the name of the database you want to create. MongoDB will create the database if it does not exist, and make a connection to it. import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] Important: In MongoDB, a database is not created until it gets content! MongoDB waits until you have created a collection (table), with at least one document (record) before it actually creates the database (and collection ). Check if Database Exists Remember: In MongoDB, a database is not created until it gets content, so if this is your first time creating a database, you should complete the next two chapters (create collection and create document) before you check if the database exists! You can check if a database e

PYTHON MONGODB

M ONGODB MongoDB MongoDB stores data in JSON-like documents, which makes the database very flexible and scalable. To be able to experiment with the code examples in this tutorial, you will need access to a MongoDB database. You can download a free MongoDB database at https://www.mongodb.com. Or get started right away with a MongoDB cloud service at https://www.mongodb.com/cloud/atlas. PyMongo Python needs a MongoDB driver to access the MongoDB database. In this tutorial we will use the MongoDB driver "PyMongo". We recommend that you use PIP to install "PyMongo". PIP is most likely already installed in your Python environment. Navigate your command line to the location of PIP, and type the following: Test PyMongo To test if the installation was successful, or if you already have "pymongo" installed, create a Python page with the following content: import pymongo If the above code was executed with no errors, "pymongo" is