Search by ObjectId in mongodb with PyMongo – Python

10 Jun, 2022
MongoDB is NoSQL Document-oriented database. In MongoDB, the data are stored in a JSON-like document structure instead of storing data in columns and rows manner. MongoDB is flexible for storing semi-structured and unstructured data. MongoDB is used for high-volume data storage and can scale horizontally.
ObjectId: ObjectId class is a 12-byte binary BSON type, in which 4 bytes of the timestamp of creation, 5 bytes of a random value, and 3 bytes of incrementing counter. ObjectId is the default primary key for MongoDB documents and is usually found in “_id” field.
eg : { "_id" : ObjectId("54759eb3c090d83494e2d804") }
PyMongo: PyMongo is a native Python driver for MongoDB. It allows interaction with MongoDB Database through Python.
Step 1: Make sure to start the MongoDB database locally on the default port (27017). Connecting to MongoDB, accessing the database, and collecting objects.
Python3
# importing MongoClient from pymongofrom pymongo import MongoClient # importing ObjectId from bson libraryfrom bson.objectid import ObjectId # Establishing connection with# mongodb on localhostclient = MongoClient('127.0.0.1', 27017) # Access database objectdb = client['database'] # Access collection objectcollection = db['collection']
Step 2: Querying MongoDB with find_one().
Syntax:
find_one(filter=None, *args, **kwargs)
filter(optional): query filter that selects which documents should be included in the result set.
*args (optional): any additional positional arguments
*kwargs (optional): any additional keyword arguments
Example 1: In this example, we have already stored the ObjectId object instance, then use the stored object instance to search for the document.
Python3
# inserts data into collection and# returns an object of type objectIdobjInstance = collection.insert_one({"name": "sam", "age": 20}).inserted_id # search MongoDB with# an object of type objectIdcollection.find_one(objInstance)
Output:
Example 2: In this example, we have the hex string not an object of ObjectId. We import ObjectId from the bson library to search the document.
Python3
# use the string object id# and objectId object to# create object of type ObjectIdid = "5fec2c0b348df9f22156cc07"objInstance = ObjectId(id) collection.find_one({"_id": objInstance}) # below line works same as the abovecollection.find_one({"_id": ObjectId(id)})collection.find_one(ObjectId(id))
Output:
Example 3: In this example, we advance the search by specifying projections that is which field we want to include/exclude in the result set. The below projection will return the entire document without the “_id” field.
Python3
# search document with filter# first parameter is search query# second parameter is filter query# you can as many fields you want# you can specify either 1 or 0# in filter fields# if you specify 0 the field will# be eliminated form the resultquery = {"_id": ObjectId(id)} filter = {"_id": 0} collection.find_one(query, filter)
Output:
ruhelaa48
sumitgumber28
sweetyty
saurabh1990aror
khushb99
Picked
Python-mongoDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function