Monday, April 29, 2019

Python MongoDB Integeration with Examples

You can download a free MongoDB database at https://www.mongodb.com.

Install the python mangodb driver:

C:\Users\Nethra>python -m pip install pymongo
Collecting pymongo
  Downloading https://files.pythonhosted.org/packages/92/d2/6993655f5c46755cf3385ef8cec78f49909e035777724a0bf02251de733f/pymongo-3.8.0-cp37-cp37m-win32.whl (312kB)
    100% |████████████████████████████████| 317kB 729kB/s
Installing collected packages: pymongo
Successfully installed pymongo-3.8.0
You are using pip version 19.0.3, however version 19.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

Creating a Database
Important: In MongoDB, a database is not created until it gets content!
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb=myclient["mydatabase"]
Check if Database Exists
>>> print(myclient.list_database_names())
['admin', 'config', 'local']
>>> dblist=myclient.list_database_names()
>>> if "mydatabase" in dblist:
...     print("The database exists.")

Create a collection:
A collection in MongoDB is the same as a table in SQL databases.
Important: In MongoDB, a collection is not created until it gets content!
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol=mydb["customes"]
>>> print(mydb.list_collection_names())
[]
>>> collist=mydb.list_collection_names()
>>> if "customers" in collist:
...     print("The collection exists")

Insert Into Collection

A document in MongoDB is the same as a record in SQL databases
>>> 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)
Return the _id Field
>>> x = mycol.insert_one(mydict)
>>> print(x.inserted_id)
5cc74f3ae1ceb9d5e0930979

Insert Multiple Documents
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>>
>>> mylist = [
...   { "name": "Amy", "address": "Apple st 652"},
...   { "name": "Hannah", "address": "Mountain 21"},
...   { "name": "Michael", "address": "Valley 345"},
...   { "name": "Sandy", "address": "Ocean blvd 2"},
...   { "name": "Betty", "address": "Green Grass 1"},
...   { "name": "Richard", "address": "Sky st 331"},
...   { "name": "Susan", "address": "One way 98"},
...   { "name": "Vicky", "address": "Yellow Garden 2"},
...   { "name": "Ben", "address": "Park Lane 38"},
...   { "name": "William", "address": "Central st 954"},
...   { "name": "Chuck", "address": "Main Road 989"},
...   { "name": "Viola", "address": "Sideway 1633"}
... ]
>>>
>>> x = mycol.insert_many(mylist)
>>>
>>> #print list of the _id values of the inserted documents:
... print(x.inserted_ids)

Insert Multiple Documents, with Specified IDs
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>>
>>> mylist = [
...   { "_id": 1, "name": "John", "address": "Highway 37"},
...   { "_id": 2, "name": "Peter", "address": "Lowstreet 27"},
...   { "_id": 3, "name": "Amy", "address": "Apple st 652"},
...   { "_id": 4, "name": "Hannah", "address": "Mountain 21"},
...   { "_id": 5, "name": "Michael", "address": "Valley 345"},
...   { "_id": 6, "name": "Sandy", "address": "Ocean blvd 2"},
...   { "_id": 7, "name": "Betty", "address": "Green Grass 1"},
...   { "_id": 8, "name": "Richard", "address": "Sky st 331"},
...   { "_id": 9, "name": "Susan", "address": "One way 98"},
...   { "_id": 10, "name": "Vicky", "address": "Yellow Garden 2"},
...   { "_id": 11, "name": "Ben", "address": "Park Lane 38"},
...   { "_id": 12, "name": "William", "address": "Central st 954"},
...   { "_id": 13, "name": "Chuck", "address": "Main Road 989"},
...   { "_id": 14, "name": "Viola", "address": "Sideway 1633"}
... ]
>>>
>>> x = mycol.insert_many(mylist)
>>>
>>> #print list of the _id values of the inserted documents:
... print(x.inserted_ids)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

Python MongoDB Find(Select)
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>>
>>> x = mycol.find_one()
>>>
>>> print(x)
{'_id': ObjectId('5cc74eebe1ceb9d5e0930978'), 'name': 'John', 'address': 'Highway 37'}

Findall:
>>> import pymongo
>>>
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>>
>>> for x in mycol.find():
...   print(x)
...
{'_id': ObjectId('5cc74eebe1ceb9d5e0930978'), 'name': 'John', 'address': 'Highway 37'}
{'_id': ObjectId('5cc74f3ae1ceb9d5e0930979'), 'name': 'Peter', 'address': 'Lowstreet 27'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097b'), 'name': 'Amy', 'address': 'Apple st 652'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097c'), 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097d'), 'name': 'Michael', 'address': 'Valley 345'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097e'), 'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097f'), 'name': 'Betty', 'address': 'Green Grass 1'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930980'), 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930981'), 'name': 'Susan', 'address': 'One way 98'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930982'), 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930983'), 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930984'), 'name': 'William', 'address': 'Central st 954'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930985'), 'name': 'Chuck', 'address': 'Main Road 989'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930986'), 'name': 'Viola', 'address': 'Sideway 1633'}
{'_id': 1, 'name': 'John', 'address': 'Highway 37'}

Return Only Some Fields

>>> for x in mycol.find({},{ "_id": 0, "name": 1, "address": 1 }):
...     print(x)
...
{'name': 'John', 'address': 'Highway 37'}
{'name': 'Peter', 'address': 'Lowstreet 27'}
{'name': 'Amy', 'address': 'Apple st 652'}
{'name': 'Hannah', 'address': 'Mountain 21'}
{'name': 'Michael', 'address': 'Valley 345'}
{'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'name': 'Betty', 'address': 'Green Grass 1'}
{'name': 'Richard', 'address': 'Sky st 331'}
{'name': 'Susan', 'address': 'One way 98'}
{'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'name': 'Ben', 'address': 'Park Lane 38'}
{'name': 'William', 'address': 'Central st 954'}
{'name': 'Chuck', 'address': 'Main Road 989'}
{'name': 'Viola', 'address': 'Sideway 1633'}
{'name': 'John', 'address': 'Highway 37'}
{'name': 'Peter', 'address': 'Lowstreet 27'}
{'name': 'Amy', 'address': 'Apple st 652'}
{'name': 'Hannah', 'address': 'Mountain 21'}
{'name': 'Michael', 'address': 'Valley 345'}
{'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'name': 'Betty', 'address': 'Green Grass 1'}
{'name': 'Richard', 'address': 'Sky st 331'}
{'name': 'Susan', 'address': 'One way 98'}
{'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'name': 'Ben', 'address': 'Park Lane 38'}
{'name': 'William', 'address': 'Central st 954'}
{'name': 'Chuck', 'address': 'Main Road 989'}
{'name': 'Viola', 'address': 'Sideway 1633'}

Excluding the Address:
>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>>
>>> for x in mycol.find({},{ "address": 0 }):
...   print(x)
...
{'_id': ObjectId('5cc74eebe1ceb9d5e0930978'), 'name': 'John'}
{'_id': ObjectId('5cc74f3ae1ceb9d5e0930979'), 'name': 'Peter'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097b'), 'name': 'Amy'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097c'), 'name': 'Hannah'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097d'), 'name': 'Michael'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097e'), 'name': 'Sandy'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097f'), 'name': 'Betty'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930980'), 'name': 'Richard'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930981'), 'name': 'Susan'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930982'), 'name': 'Vicky'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930983'), 'name': 'Ben'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930984'), 'name': 'William'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930985'), 'name': 'Chuck'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930986'), 'name': 'Viola'}
{'_id': 1, 'name': 'John'}
{'_id': 2, 'name': 'Peter'}
{'_id': 3, 'name': 'Amy'}
{'_id': 4, 'name': 'Hannah'}
{'_id': 5, 'name': 'Michael'}
{'_id': 6, 'name': 'Sandy'}
{'_id': 7, 'name': 'Betty'}
{'_id': 8, 'name': 'Richard'}
{'_id': 9, 'name': 'Susan'}
{'_id': 10, 'name': 'Vicky'}
{'_id': 11, 'name': 'Ben'}
{'_id': 12, 'name': 'William'}
{'_id': 13, 'name': 'Chuck'}
{'_id': 14, 'name': 'Viola'}

Filter the Result:
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> myquery = { "address": "Park Lane 38" }
>>> mydoc = mycol.find(myquery)
>>> for x in mydoc:
...   print(x)
...
{'_id': ObjectId('5cc75008e1ceb9d5e0930983'), 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': 11, 'name': 'Ben', 'address': 'Park Lane 38'}

Advanced Query
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> myquery = { "address": { "$gt": "S" } }
>>> mydoc = mycol.find(myquery)
>>> for x in mydoc:
...   print(x)
...
{'_id': ObjectId('5cc75008e1ceb9d5e093097d'), 'name': 'Michael', 'address': 'Valley 345'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930980'), 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930982'), 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930986'), 'name': 'Viola', 'address': 'Sideway 1633'}
{'_id': 5, 'name': 'Michael', 'address': 'Valley 345'}
{'_id': 8, 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': 10, 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': 14, 'name': 'Viola', 'address': 'Sideway 1633'}

Filter With Regular Expressions
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> myquery = { "address": { "$regex": "^S" } }
>>> mydoc = mycol.find(myquery)
>>> for x in mydoc:
...   print(x)
...
{'_id': ObjectId('5cc75008e1ceb9d5e0930980'), 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930986'), 'name': 'Viola', 'address': 'Sideway 1633'}
{'_id': 8, 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': 14, 'name': 'Viola', 'address': 'Sideway 1633'}

Sort the Result:
>>> 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)
...
{'_id': ObjectId('5cc75008e1ceb9d5e093097b'), 'name': 'Amy', 'address': 'Apple st 652'}
{'_id': 3, 'name': 'Amy', 'address': 'Apple st 652'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930983'), 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': 11, 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097f'), 'name': 'Betty', 'address': 'Green Grass 1'}
{'_id': 7, 'name': 'Betty', 'address': 'Green Grass 1'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930985'), 'name': 'Chuck', 'address': 'Main Road 989'}
{'_id': 13, 'name': 'Chuck', 'address': 'Main Road 989'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097c'), 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': 4, 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': ObjectId('5cc74eebe1ceb9d5e0930978'), 'name': 'John', 'address': 'Highway 37'}
{'_id': 1, 'name': 'John', 'address': 'Highway 37'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097d'), 'name': 'Michael', 'address': 'Valley 345'}
{'_id': 5, 'name': 'Michael', 'address': 'Valley 345'}
{'_id': ObjectId('5cc74f3ae1ceb9d5e0930979'), 'name': 'Peter', 'address': 'Lowstreet 27'}
{'_id': 2, 'name': 'Peter', 'address': 'Lowstreet 27'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930980'), 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': 8, 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097e'), 'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'_id': 6, 'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930981'), 'name': 'Susan', 'address': 'One way 98'}
{'_id': 9, 'name': 'Susan', 'address': 'One way 98'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930982'), 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': 10, 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930986'), 'name': 'Viola', 'address': 'Sideway 1633'}
{'_id': 14, 'name': 'Viola', 'address': 'Sideway 1633'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930984'), 'name': 'William', 'address': 'Central st 954'}
{'_id': 12, 'name': 'William', 'address': 'Central st 954'}

Sort Descending

sort("name", 1) #ascending
sort("name", -1) #descending 


>>> 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)
...
{'_id': ObjectId('5cc75008e1ceb9d5e0930984'), 'name': 'William', 'address': 'Central st 954'}
{'_id': 12, 'name': 'William', 'address': 'Central st 954'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930986'), 'name': 'Viola', 'address': 'Sideway 1633'}
{'_id': 14, 'name': 'Viola', 'address': 'Sideway 1633'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930982'), 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': 10, 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930981'), 'name': 'Susan', 'address': 'One way 98'}
{'_id': 9, 'name': 'Susan', 'address': 'One way 98'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097e'), 'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'_id': 6, 'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930980'), 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': 8, 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': ObjectId('5cc74f3ae1ceb9d5e0930979'), 'name': 'Peter', 'address': 'Lowstreet 27'}
{'_id': 2, 'name': 'Peter', 'address': 'Lowstreet 27'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097d'), 'name': 'Michael', 'address': 'Valley 345'}
{'_id': 5, 'name': 'Michael', 'address': 'Valley 345'}
{'_id': ObjectId('5cc74eebe1ceb9d5e0930978'), 'name': 'John', 'address': 'Highway 37'}
{'_id': 1, 'name': 'John', 'address': 'Highway 37'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097c'), 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': 4, 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930985'), 'name': 'Chuck', 'address': 'Main Road 989'}
{'_id': 13, 'name': 'Chuck', 'address': 'Main Road 989'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097f'), 'name': 'Betty', 'address': 'Green Grass 1'}
{'_id': 7, 'name': 'Betty', 'address': 'Green Grass 1'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930983'), 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': 11, 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097b'), 'name': 'Amy', 'address': 'Apple st 652'}
{'_id': 3, 'name': 'Amy', 'address': 'Apple st 652'}

Delete Document
>>> 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
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> myquery = { "address": {"$regex": "^S"} }
>>> x = mycol.delete_many(myquery)
>>> print(x.deleted_count, " documents deleted.")
4  documents deleted.

Delete All Documents in a Collection
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> x = mycol.delete_many({})
>>> print(x.deleted_count, " documents deleted.")
23  documents deleted.

Delete collection:
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> mycol.drop()
Update Collection:
>>> 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)
...
{'_id': ObjectId('5cc7589de1ceb9d5e0930997'), 'name': 'Amy', 'address': 'Apple st 652'}
{'_id': ObjectId('5cc7589de1ceb9d5e0930998'), 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': ObjectId('5cc7589de1ceb9d5e0930999'), 'name': 'Michael', 'address': 'Canyon 123'}
{'_id': ObjectId('5cc7589de1ceb9d5e093099a'), 'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'_id': ObjectId('5cc7589de1ceb9d5e093099b'), 'name': 'Betty', 'address': 'Green Grass 1'}
{'_id': ObjectId('5cc7589de1ceb9d5e093099c'), 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': ObjectId('5cc7589de1ceb9d5e093099d'), 'name': 'Susan', 'address': 'One way 98'}
{'_id': ObjectId('5cc7589de1ceb9d5e093099e'), 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': ObjectId('5cc7589de1ceb9d5e093099f'), 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': ObjectId('5cc7589de1ceb9d5e09309a0'), 'name': 'William', 'address': 'Central st 954'}
{'_id': ObjectId('5cc7589de1ceb9d5e09309a1'), 'name': 'Chuck', 'address': 'Main Road 989'}
{'_id': ObjectId('5cc7589de1ceb9d5e09309a2'), 'name': 'Viola', 'address': 'Sideway 1633'}


Update Many:
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> myquery = { "address": { "$regex": "^S" } }
>>> newvalues = { "$set": { "name": "Minnie" } }
>>> x = mycol.update_many(myquery, newvalues)
>>> print(x.modified_count, "documents updated.")
2 documents updated.

Limit the Result
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> myresult = mycol.find().limit(5)
>>> #print the result:
... for x in myresult:
...   print(x)
...
{'_id': ObjectId('5cc7589de1ceb9d5e0930997'), 'name': 'Amy', 'address': 'Apple st 652'}
{'_id': ObjectId('5cc7589de1ceb9d5e0930998'), 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': ObjectId('5cc7589de1ceb9d5e0930999'), 'name': 'Michael', 'address': 'Canyon 123'}
{'_id': ObjectId('5cc7589de1ceb9d5e093099a'), 'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'_id': ObjectId('5cc7589de1ceb9d5e093099b'), 'name': 'Betty', 'address': 'Green Grass 1'}
>>>





Python Important business operation(Reverse the string and Remove the duplicates)

How to remove the duplicates:
>>> mylist=["a","b","a","c","c"]
>>> mylist=list(dict.fromkeys(mylist))
>>> print(mylist)
['a', 'b', 'c']

How to remove duplicates through Function
>>> def my_function(x):
...     return list(dict.fromkeys(x))
...
>>> mylist=my_function(["a","b","a","c","c"])
>>> print(mylist)
['a', 'b', 'c']

Reverse the String:
>>> txt="Hello World"[::-1]
>>> print(txt)
dlroW olleH

Reverse a String through Function:
>>> def my_function(x):
...     return x[::-1]
...
>>> mytxt=my_function("I wonder how this text looks like backwards")
>>> print(mytxt)
sdrawkcab ekil skool txet siht woh rednow I

Monday, April 15, 2019

Python Keywords Examples


Python Keywords

and A logical operator

x = (5 > 3 and 5 < 10)

print(x)



if 5 > 3 and 5 < 10:

  print("Both statements are True")

else:

  print("At least one of the statements are False")



True

Both statements are True

as To create an alias

import calendar as c

print(c.month_name[1])



January

assert For debugging

x = "hello"

#if condition returns True, then nothing happens:

assert x == "hello"



#if condition returns False, AssertionError is raised:

assert x == "goodbye", "x should be 'hello'"



Traceback (most recent call last):

  File "main.py", line 6, in

    assert x == "goodbye", "x should be 'hello'"

AssertionError: x should be 'hello'

break To break out of a loop

for i in range(9):

  if i > 3:

    break

  print(i)

0

1

2

3

i = 1

while i < 9:

  print(i)

  if i == 3:

    break

  i += 1

1

2

3

class To define a class

class Person:

  name = "John"

  age = 36



p1 = Person()

print(p1.name)

John

continue To continue to the next iteration of a loop

for i in range(9):

  if i == 3:

    continue

  print(i)

0

1

2

4

5

6

7

8

i = 0

while i < 9:

  i += 1

  if i == 3:

    continue

  print(i)

1

2

4

5

6

7

8

9

def To define a function

def my_function():

  print("Hello from a function")

my_function()



Hello from a function



del To delete an object

class MyClass:

  name = "John"

del myClass

print(myClass)

Traceback (most recent call last):

  File "main.py", line 3, in

    del myClass

NameError: name 'myClass' is not defined



x = "hello"

del x

print(x)

Traceback (most recent call last):

  File "main.py", line 3, in

    print(x)

NameError: name 'x' is not defined



x = ["apple", "banana", "cherry"]

del x[0]

print(x)

['banana', 'cherry']



elif Used in conditional statements, same as else if

for i in range(-5, 5):

  if i > 0:

    print("YES")

  elif i == 0:

    print("WHATEVER")

  else:

    print("NO")

NO

NO

NO

NO

NO

WHATEVER

YES

YES

YES

YES



else Used in conditional statements

x = 2

if x > 3:

  print("YES")

else:

  print("NO")

NO



x = 5

try:

  x > 10

except:

  print("Something went wrong")

else:

  print("The 'Try' code was executed without raising any errors!")

The 'Try' code was executed without raising any errors!



except Used with exceptions, what to do when an exception occurs

try:

  x > 3

except:

  print("Something went wrong")

Something went wrong



x = "hello"



try:

  x > 3

except NameError:

  print("You have a variable that is not defined.")

except TypeError:

  print("You are comparing values of different type")

You are comparing values of different type



try:

  x = 1/0

except NameError:

  print("You have a variable that is not defined.")

except TypeError:

  print("You are comparing values of different type")

except:

  print("Something else went wrong")



Something else went wrong



x = 1



try:

  x > 10

except NameError:

  print("You have a variable that is not defined.")

except TypeError:

  print("You are comparing values of different type")

else:

  print("The 'Try' code was executed without raising any errors!")

The 'Try' code was executed without raising any errors!



False Boolean value, result of comparison operations

print(5 > 6)



print(4 in [1,2,3])



print("hello" is "goodbye")



print(5 == 6)



print(5 == 6 or 6 == 7)



print(5 == 6 and 6 == 7)



print("hello" is not "hello")



print(not(5 == 5))



print(3 not in [1,2,3])

False

False

False

False

False

False

False

False

False



finally Used with exceptions, a block of code that will be executed no matter if there is an exception or not

try:

  x > 3

except:

  print("Something went wrong")

else:

  print("Nothing went wrong")

finally:

  print("The try...except block is finished")

Something went wrong

The try...except block is finished



for To create a for loop

for x in range(1, 9):

  print(x)

1

2

3

4

5

6

7

8

fruits = ["apple", "banana", "cherry"]

for x in fruits:

  print(x)

apple

banana

cherry



from To import specific parts of a module

from datetime import time

x = time(hour=15)

print(x)

15:00:00



global To declare a global variable



def myfunction():

  global x

  x = "hello"



#execute the function:

myfunction()



#x should now be global, and accessible in the global scope.

print(x)

hello

if  make a conditional statement

x = 5

if x > 3:

  print("YES")

YES x = 5

if x > 6:

  print("YES")

else:

  print("NO")

NO

import To import a module

import datetime

x = datetime.datetime.now()

print(x)

2019-04-15 20:41:05.252261

in To check if a value is present in a list, tuple, etc.

fruits = ["apple", "banana", "cherry"]

if "banana" in fruits:

  print("yes")

yes

fruits = ["apple", "banana", "cherry"]

for x in fruits:

  print(x)

apple

banana

cherry

is To test if two variables are equal

x = ["apple", "banana", "cherry"]



y = x



print(x is y)

True

x = ["apple", "banana", "cherry"]



y = ["apple", "banana", "cherry"]



print(x is y)

False

lambda To create an anonymous function

x = lambda a : a + 10



print(x(5))

15

x = lambda a, b, c : a + b + c



print(x(5, 6, 2))

13

None Represents a null value

x = None

print(x)



x = None

if x:

  print("Do you think None is True")

else:

  print("None is not True...")

None

None is not True...

nonlocal To declare a non-local variable

def myfunc1():

  x = "John"

  def myfunc2():

    x = "hello"

  myfunc2()

  return x



print(myfunc1())

John

not A logical operator

x = False

print(not x)

True

or A logical operator

x = (5 > 3 or 5 > 10)

print(x)

if 5 > 3 or 5 > 10:

  print("At least one of the statements are True")

else:

  print("None of the statements are True")

True

At least one of the statements are True

pass A null statement, a statement that will do nothing

class Person:

  pass



raise To raise an exception

x = -1

if x < 0:

  raise Exception("Sorry, no numbers below zero")

Traceback (most recent call last):

  File "main.py", line 3, in

    raise Exception("Sorry, no numbers below zero")

Exception: Sorry, no numbers below zero

x = "hello"



if not type(x) is int:

  raise TypeError("Only integers are allowed")

Traceback (most recent call last):

  File "main.py", line 4, in

    raise TypeError("Only integers are allowed")

TypeError: Only integers are allowed

return To exit a function and return a value

def myfunction():

  return 3+3



print(myfunction())

6

def myfunction():

  return 3+3

  print("Hello, World!")



print(myfunction())



6

True Boolean value, result of comparison operations

print(5 < 6)



print(2 in [1,2,3])



print(5 is 5)



print(5 == 5)



print(5 == 5 or 6 == 7)



print(5 == 5 and 7 == 7)



print("hello" is not "goodbye")



print(not(5 == 7))



print(4 not in [1,2,3])

True

True

True

True

True

True

True

True

True

try To make a try...except statement

try:

  x > 3

except:

  print("Something went wrong")

Something went wrong

try:

  x > 3

except:

  Exception("Something went wrong")



while To create a while loop

x = 0



while x < 9:

  print(x)

  x = x + 1

0

1

2

3

4

5

6

7

8


Python Challenges Program

Challenges program: program 1: #Input :ABAABBCA #Output: A4B3C1 str1="ABAABBCA" str2="" d={} for x in str1: d[x]=d...