MongoDB with Python - pyMongo - Intermediate II

In [1]:
import pprint
from pymongo import MongoClient
In [2]:
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")

db=con.Cluster0
print(db.list_collection_names())

# checking doc count
db.user.count_documents({})
['user', 'movies_scratch', 'testidx', 'movies_initial']
Out[2]:
78

Query by Object ID

In [3]:
db.user.find_one()
Out[3]:
{'_id': ObjectId('5c16e863817810ed3fc5e5f9'),
 'Fname': 'atul',
 'Lname': 'Singh',
 'Grade': 12.0,
 'College': 'SGM',
 'Job': 'Student',
 'Address': 'Young St.'}
In [4]:
# if I want to query the data based on the object id 
db.user.find_one({'_id':'5c16e863817810ed3fc5e5f9'})
In [5]:
db.user.find_one({'_id':ObjectId('5c16e863817810ed3fc5e5f9')})
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-5-877f3040eede> in <module>
----> 1 db.user.find_one({'_id':ObjectId('5c16e863817810ed3fc5e5f9')})

NameError: name 'ObjectId' is not defined

Import ObjectID from python bson library

In [6]:
from bson.objectid import ObjectId
db.user.find_one({'_id':ObjectId('5c16e863817810ed3fc5e5f9')})
Out[6]:
{'_id': ObjectId('5c16e863817810ed3fc5e5f9'),
 'Fname': 'atul',
 'Lname': 'Singh',
 'Grade': 12.0,
 'College': 'SGM',
 'Job': 'Student',
 'Address': 'Young St.'}

Get ID from Query

In [7]:
def getId():
    return db.user.find_one({},{'_id':1})['_id']
In [8]:
getId()
Out[8]:
ObjectId('5c16e863817810ed3fc5e5f9')

Get Record from ObjectId

In [9]:
from bson.objectid import ObjectId
def getRec(ID):
    return db.user.find_one({'_id':ID})
In [10]:
ID=getId()
getRec(ID)
Out[10]:
{'_id': ObjectId('5c16e863817810ed3fc5e5f9'),
 'Fname': 'atul',
 'Lname': 'Singh',
 'Grade': 12.0,
 'College': 'SGM',
 'Job': 'Student',
 'Address': 'Young St.'}