Friday, March 31, 2023

Deletion

The delete_one function deletes a single document from the MongoDB collection. Previously we had inserted the document for a user named Mike. Let’s have a look at the MongoDB document inserted:

table.find_one({'name':'Mike'})


We will now delete this MongoDB document:

table.delete_one({'name':'Mike'})


Let’s try to fetch this document after deletion. If this document is not available in our MongoDB collection, the find_one function will return nothing.

table.find_one({'name':'Mike'}) Output: Nothing is returned.

Since we get nothing in return, it means that the MongoDB document doesn’t exist anymore.

As we saw that the insert_many function is used to insert multiple documents in MongoDB collection, delete_many is used to delete multiple documents at once. Let’s try to delete two MongoDB documents by the name field:

myquery = ({ "name":{"$in": ["Gyan","Eliot"]}})

x = table.delete_many(myquery)

print(x.deleted_count, " documents deleted.") 

Here, the deleted count stores the number of deleted MongoDB documents during the operation. The ‘$in’ is an operator in MongoDB.


Share:

Friday, March 17, 2023

Filter Conditions

We have seen how to fetch data from MongoDB using find and find_one functions. But, we don’t need to fetch all the documents all the time. This is where we apply some filter conditions.

Previously we have inserted a document to the MongoDB collection with the name  field as Gyan. Let’s see how to fetch that MongoDB document using the filter condition:

table.find_one({"name":'Gyan'})


mongodb python filter

Here, we have fetched the document using the name which is a string argument. On the other hand, we have seen in the previous example that final. inserted_ids contains the Ids of the inserted documents.

If we apply the filter condition on the _id field, it will return nothing because their datatype is ObjectId. This is not the built-in datatype. We need to convert the string value to ObjectId type to apply the filter condition on _id . So first, we will define a function to convert the string value then we will fetch the MongoDB document:

from bson.objectid import ObjectId

post_id=final.inserted_ids[0]

def parser(post_id):

    document = table.find_one({'_id': ObjectId(post_id)})

    return document

parser(post_id)





Share: