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

Popular posts from this blog

ERR: error parsing query: found influx, expected SELECT, DELETE, SHOW, CREATE, DROP, EXPLAIN, GRANT, REVOKE, ALTER, SET, KILL at line

How To Convert Html File/URL/String Into Image Using Python

How to get Full URL or get absolute url In Django