Search by ObjectId in mongodb with PyMongo - Python
Last Updated :
14 Dec, 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.
Please import Objectid from pymongo
from pymongo import ObjectId
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 pymongo
from pymongo import MongoClient
# importing ObjectId from bson library
from bson.objectid import ObjectId
# Establishing connection with
# mongodb on localhost
client = MongoClient('127.0.0.1', 27017)
# Access database object
db = client['database']
# Access collection object
collection = 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 objectId
objInstance = collection.insert_one({"name": "sam", "age": 20}).inserted_id
# search MongoDB with
# an object of type objectId
collection.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 ObjectId
id = "5fec2c0b348df9f22156cc07"
objInstance = ObjectId(id)
collection.find_one({"_id": objInstance})
# below line works same as the above
collection.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 result
query = {"_id": ObjectId(id)}
filter = {"_id": 0}
collection.find_one(query, filter)
Output:

Similar Reads
How to update record without objectID in mongoose? Mongoose is an ODM(Object Data Library) for MongoDB in Node JS that helps to write schema, validation and business logic in a simple way without the hassle of native MongoDB boilerplate. PrerequisitesUnderstanding of Mongoose and MongoDBData Modeling and Schema DesignMongoose Query MethodsApproach t
3 min read
Python - SavedSearch object in Tweepy Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from
2 min read
Python MongoDB - find_one Query This article focus on the find_one() method of the PyMongo library. find_one() is used to find the data from MongoDB. Prerequisites: MongoDB Python Basics Let's begin with the find_one() method:Importing PyMongo Module: Import the PyMongo module using the command:from pymongo import MongoClientIf Mo
3 min read
Python MongoDB - find_one_and_update Query The function find_one_and_update() actually finds and updates a MongoDB document. Though default-wise this function returns the document in its original form and to return the updated document return_document has to be implemented in the code. Syntax:Â coll.find_one_and_update(filter, update, option
2 min read
How to Converting ObjectId to String in MongoDB In MongoDB, documents are uniquely identified by a field called ObjectId. While ObjectId is a unique identifier for each document there may be scenarios where we need to convert it to a string format for specific operations or data manipulation. In this article, we'll learn about the process of conv
4 min read
How to Query MongoDB ObjectId by Date? MongoDB ObjectId is an important element in document identification, but can it help us with date-based queries? Understanding the ObjectId's structure and its potential for querying by date opens up new possibilities for data retrieval and analysis. In this article, We will learn about how to perfo
4 min read
Python MongoDB - insert_one Query MongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs. MongoDB is developed by MongoDB Inc. and was initially released on 11 February 2009. It is written in C++, Go,
3 min read
Indexing in MongoDB using Python By creating indexes in a MongoDB collection, query performance is enhanced because they store the information in such a manner that traversing it becomes easier and more efficient. There is no need for a full scan as MongoDB can search the query through indexes. Thus it restricts the number of docum
2 min read
How to Creating Mongoose Schema with an Array of ObjectID In Mongoose, a powerful MongoDB object modeling tool for Node.js, schemas define the structure of documents within a collection. Sometimes, you may need to create a schema with an array of ObjectIDs to represent relationships between documents in different collections. This article will explain how
4 min read
Using $search and Compound Operators in MongoDB In MongoDB, advanced querying techniques allow users to efficiently manage and retrieve data. The $search operator is a powerful tool for performing text searches within collections while compound operators like $and, $or, and $nor enable the creation of complex queries by combining multiple conditi
5 min read