MongoDB with Python - pyMongo - Basic I

In [95]:
from pymongo import MongoClient
import pprint

Connect to DB

In [96]:
con = MongoClient("mongodb://mdbuser:[email protected]:27017,cluster0-shard-00-01-mswpe.mongodb.net:27017,\
cluster0-shard-00-02-mswpe.mongodb.net:27017/Cluster0?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true")
In [97]:
con.list_database_names()
Out[97]:
['Cluster0', 'admin', 'local']

Using DB

In [98]:
db = con.Cluster0
In [99]:
# Listing collections
db.list_collection_names()
Out[99]:
['user', 'movies_scratch', 'testidx', 'movies_initial']
In [100]:
# taking record count in collection movies_initial
print(db.movies_initial.estimated_document_count())
46014

Read - R (CRUD)

In [101]:
db.movies_initial.find_one()
Out[101]:
{'_id': ObjectId('5c15fe3932245fbaaa56d6ba'),
 'imdbID': 1,
 'title': 'Carmencita',
 'year': 1894,
 'rating': 'NOT RATED',
 'runtime': '1 min',
 'genre': 'Documentary, Short',
 'released': '',
 'director': 'William K.L. Dickson',
 'writer': '',
 'cast': 'Carmencita',
 'metacritic': '',
 'imdbRating': 5.9,
 'imdbVotes': 1032,
 'poster': 'http://ia.media-imdb.com/images/M/[email protected]@._V1_SX300.jpg',
 'plot': 'Performing on what looks like a small wooden stage, wearing a dress with a hoop skirt and white high-heeled pumps, Carmencita does a dance with kicks and twirls, a smile always on her face.',
 'fullplot': 'Performing on what looks like a small wooden stage, wearing a dress with a hoop skirt and white high-heeled pumps, Carmencita does a dance with kicks and twirls, a smile always on her face.',
 'language': '',
 'country': 'USA',
 'awards': '',
 'lastupdated': '2015-08-26 00:03:45.040000000',
 'type': 'movie'}
In [102]:
db.movies_initial.find_one({"year":1987})
Out[102]:
{'_id': ObjectId('5c15fe4032245fbaaa5704eb'),
 'imdbID': 80629,
 'title': 'Dinosaurs!',
 'year': 1987,
 'rating': '',
 'runtime': '30 min',
 'genre': 'Animation, Short',
 'released': '',
 'director': 'Ray Cioni, Kelli Bixler, Will Vinton',
 'writer': 'Virginia Theimer Clapper (screenplay), Susan Shadburne',
 'cast': 'Michele Mariana, Josette DiCarlo, Fred Savage',
 'metacritic': '',
 'imdbRating': 7.8,
 'imdbVotes': 143,
 'poster': '',
 'plot': "Richard gives a class report on dinosaurs, with the help of an animated chalkboard and Will Vinton's claymation dinosaurs.",
 'fullplot': "Richard gives a class report on dinosaurs, with the help of an animated chalkboard and Will Vinton's claymation dinosaurs.",
 'language': 'English',
 'country': 'USA',
 'awards': '',
 'lastupdated': '2015-04-30 02:13:50.533000000',
 'type': 'movie'}

Count

In [103]:
docs = db.movies_initial.find({"year":1987})
print(docs.count())
print(db.movies_initial.count_documents({"year":1987}))
470
470
C:\Anaconda3\envs\mdb\lib\site-packages\ipykernel_launcher.py:2: DeprecationWarning: count is deprecated. Use Collection.count_documents instead.
  
In [105]:
docs_list = list(docs)
pprint.pprint(docs_list[:2])
[{'_id': ObjectId('5c15fe4032245fbaaa5704eb'),
  'awards': '',
  'cast': 'Michele Mariana, Josette DiCarlo, Fred Savage',
  'country': 'USA',
  'director': 'Ray Cioni, Kelli Bixler, Will Vinton',
  'fullplot': 'Richard gives a class report on dinosaurs, with the help of an '
              "animated chalkboard and Will Vinton's claymation dinosaurs.",
  'genre': 'Animation, Short',
  'imdbID': 80629,
  'imdbRating': 7.8,
  'imdbVotes': 143,
  'language': 'English',
  'lastupdated': '2015-04-30 02:13:50.533000000',
  'metacritic': '',
  'plot': 'Richard gives a class report on dinosaurs, with the help of an '
          "animated chalkboard and Will Vinton's claymation dinosaurs.",
  'poster': '',
  'rating': '',
  'released': '',
  'runtime': '30 min',
  'title': 'Dinosaurs!',
  'type': 'movie',
  'writer': 'Virginia Theimer Clapper (screenplay), Susan Shadburne',
  'year': 1987},
 {'_id': ObjectId('5c15fe4032245fbaaa57064b'),
  'awards': '',
  'cast': '',
  'country': 'UK',
  'director': 'Keith Griffiths, Stephen Quay, Timothy Quay',
  'fullplot': 'A red-clothed puppet lives in a room with a missing wall. He '
              'rides a tricycle. Gadgets surround him. He eats dandelion '
              'tufts. A painting lies on a table in the middle of his room. He '
              'hides. A bird-man flies into the room curious about the vaguely '
              'erotic painting. Something in it moves: the bird-man looks '
              "closely, the painting clamps shut, he's ensnared. Trike-man "
              'emerges from hiding, frees a cricket from inside the table and '
              'throws the cricket into the night. He pulls a bolt of cloth '
              'through a hole in one wall, yard by yard. Trapped in the cloth '
              'is the bird-man, whose wings the trike-man clips; he cages the '
              'bird-man in his table and rides his trike maniacally around the '
              'cage.',
  'genre': 'Animation, Short',
  'imdbID': 82335,
  'imdbRating': 7.2,
  'imdbVotes': 483,
  'language': 'English',
  'lastupdated': '2015-04-02 00:52:25.153000000',
  'metacritic': '',
  'plot': 'Loosely based on the Mesopotamian "Epic of Gilgamesh", here '
          'Gilgamesh is portrayed as a grotesque, Picasso-esque being who uses '
          'a tricycle to patrol his box-shaped kingdom that hovers above a '
          'dark abyss.',
  'poster': 'http://ia.media-imdb.com/images/M/[email protected]@._V1_SX300.jpg',
  'rating': '',
  'released': '1987-04-29',
  'runtime': '11 min',
  'title': 'This Unnameable Little Broom',
  'type': 'movie',
  'writer': 'Keith Griffiths, Stephen Quay, Timothy Quay',
  'year': 1987}]
In [106]:
for doc in docs_list[:2]:
    print(doc)
{'_id': ObjectId('5c15fe4032245fbaaa5704eb'), 'imdbID': 80629, 'title': 'Dinosaurs!', 'year': 1987, 'rating': '', 'runtime': '30 min', 'genre': 'Animation, Short', 'released': '', 'director': 'Ray Cioni, Kelli Bixler, Will Vinton', 'writer': 'Virginia Theimer Clapper (screenplay), Susan Shadburne', 'cast': 'Michele Mariana, Josette DiCarlo, Fred Savage', 'metacritic': '', 'imdbRating': 7.8, 'imdbVotes': 143, 'poster': '', 'plot': "Richard gives a class report on dinosaurs, with the help of an animated chalkboard and Will Vinton's claymation dinosaurs.", 'fullplot': "Richard gives a class report on dinosaurs, with the help of an animated chalkboard and Will Vinton's claymation dinosaurs.", 'language': 'English', 'country': 'USA', 'awards': '', 'lastupdated': '2015-04-30 02:13:50.533000000', 'type': 'movie'}
{'_id': ObjectId('5c15fe4032245fbaaa57064b'), 'imdbID': 82335, 'title': 'This Unnameable Little Broom', 'year': 1987, 'rating': '', 'runtime': '11 min', 'genre': 'Animation, Short', 'released': '1987-04-29', 'director': 'Keith Griffiths, Stephen Quay, Timothy Quay', 'writer': 'Keith Griffiths, Stephen Quay, Timothy Quay', 'cast': '', 'metacritic': '', 'imdbRating': 7.2, 'imdbVotes': 483, 'poster': 'http://ia.media-imdb.com/images/M/[email protected]@._V1_SX300.jpg', 'plot': 'Loosely based on the Mesopotamian "Epic of Gilgamesh", here Gilgamesh is portrayed as a grotesque, Picasso-esque being who uses a tricycle to patrol his box-shaped kingdom that hovers above a dark abyss.', 'fullplot': "A red-clothed puppet lives in a room with a missing wall. He rides a tricycle. Gadgets surround him. He eats dandelion tufts. A painting lies on a table in the middle of his room. He hides. A bird-man flies into the room curious about the vaguely erotic painting. Something in it moves: the bird-man looks closely, the painting clamps shut, he's ensnared. Trike-man emerges from hiding, frees a cricket from inside the table and throws the cricket into the night. He pulls a bolt of cloth through a hole in one wall, yard by yard. Trapped in the cloth is the bird-man, whose wings the trike-man clips; he cages the bird-man in his table and rides his trike maniacally around the cage.", 'language': 'English', 'country': 'UK', 'awards': '', 'lastupdated': '2015-04-02 00:52:25.153000000', 'type': 'movie'}

Create - C (CRUD)

In [107]:
# any dictionary can be stored or inserted

user_1 = {'Name':'Atul', 'Age':28, 'Job':'DA', 'City':'Toronto'}
user_2 = {'Name':'Ashley', 'Age':28, 'Job':'Student', 'City':'Toronto'}
user_3 = {'Name':'Akash', 'Age':26, 'Job':'Doctor', 'City':'Toronto'}

insert_one

In [108]:
db.user.insert_one(user_1)
Out[108]:
<pymongo.results.InsertOneResult at 0x2ba05247088>
In [109]:
pprint.pprint(list(db.user.find({'City':'Toronto'})))
[{'Age': 28,
  'City': 'Toronto',
  'Job': 'Student',
  'Name': 'Ashley',
  'Org': 'IBM',
  'Province': 'ON',
  '_id': ObjectId('5c25fb93802bd976409839db')},
 {'Age': 28,
  'City': 'Toronto',
  'Job': 'DA',
  'Name': 'Atul',
  '_id': ObjectId('5c2601c0802bd976409839de')}]

insert

In [110]:
db.user.count_documents({})
Out[110]:
14
In [111]:
db.user.insert_many([user_2, user_3])
Out[111]:
<pymongo.results.InsertManyResult at 0x2ba051ea648>
In [112]:
db.user.count_documents({})
Out[112]:
16
In [113]:
pprint.pprint(list(db.user.find({'City':'Toronto'})))
[{'Age': 28,
  'City': 'Toronto',
  'Job': 'Student',
  'Name': 'Ashley',
  'Org': 'IBM',
  'Province': 'ON',
  '_id': ObjectId('5c25fb93802bd976409839db')},
 {'Age': 28,
  'City': 'Toronto',
  'Job': 'DA',
  'Name': 'Atul',
  '_id': ObjectId('5c2601c0802bd976409839de')},
 {'Age': 28,
  'City': 'Toronto',
  'Job': 'Student',
  'Name': 'Ashley',
  '_id': ObjectId('5c2601c6802bd976409839df')},
 {'Age': 26,
  'City': 'Toronto',
  'Job': 'Doctor',
  'Name': 'Akash',
  '_id': ObjectId('5c2601c6802bd976409839e0')}]

Update - U (CRUD)

collection_name.update_many([filter],[update])

In [114]:
db.user.update_many({'City':'Toronto'},{'$set':{'Org':'IBM', 'Province':'ON'}})
Out[114]:
<pymongo.results.UpdateResult at 0x2ba05363848>
In [115]:
pprint.pprint(list(db.user.find({'City':'Toronto'})))
[{'Age': 28,
  'City': 'Toronto',
  'Job': 'Student',
  'Name': 'Ashley',
  'Org': 'IBM',
  'Province': 'ON',
  '_id': ObjectId('5c25fb93802bd976409839db')},
 {'Age': 28,
  'City': 'Toronto',
  'Job': 'DA',
  'Name': 'Atul',
  'Org': 'IBM',
  'Province': 'ON',
  '_id': ObjectId('5c2601c0802bd976409839de')},
 {'Age': 28,
  'City': 'Toronto',
  'Job': 'Student',
  'Name': 'Ashley',
  'Org': 'IBM',
  'Province': 'ON',
  '_id': ObjectId('5c2601c6802bd976409839df')},
 {'Age': 26,
  'City': 'Toronto',
  'Job': 'Doctor',
  'Name': 'Akash',
  'Org': 'IBM',
  'Province': 'ON',
  '_id': ObjectId('5c2601c6802bd976409839e0')}]

collection_name.update_one([filter],[update])

In [116]:
db.user.update_one({'City':'Toronto', 'Name':'Atul'},{'$set':{'Sal':'20000$'}})
Out[116]:
<pymongo.results.UpdateResult at 0x2ba05386b88>
In [117]:
pprint.pprint(db.user.find_one({'City':'Toronto', 'Name':'Atul'}))
{'Age': 28,
 'City': 'Toronto',
 'Job': 'DA',
 'Name': 'Atul',
 'Org': 'IBM',
 'Province': 'ON',
 'Sal': '20000$',
 '_id': ObjectId('5c2601c0802bd976409839de')}

Delete - D (CRUD)

db.user.delete_one()

In [118]:
print(db.user.count_documents({}))
db.user.delete_one({'Age':26})
print(db.user.count_documents({}))
16
15

db.user.delete_many()

In [119]:
print(db.user.count_documents({'Age':28}))
db.user.delete_many({'Age':28})
print(db.user.count_documents({'Age':28}))
3
0