Mongodb Queries

First Connet with Your Database: 

from pymongo import MongoClient

mongo_client = MongoClient(host='', port='', username='',password='')

db = mongo_client[str(self.database_name)]


how to Search value on the Database:


filter query in MongoDB - {email: {"$regex": 'kings', "$options": 'i'}}

or using Python

modify_str = '^' + partner_name + '$'
filter_res = db.get_collection(collection_name).find_one(
{
'name': {"$regex": modify_str, "$options": 'i'}
}
)
if It retun None then No name match else get match documents


How to Update Many Documents at Once

res = db.get_collection(collection_name).update_many(
{},
{"$set":
{
"You_want_to_updated_key": "value"
}
},
# don't insert if no document found
upsert=False,
array_filters=None
)

$set is used to add a new key to documents if it does not exist otherwise updated the key with value

Upsert means if True then insert new document if it was not found And False then-No documented created




Comments