Work with mongodb using python
How to connect python with mongodb and create a database?
client=pymongo.MongoClient("mongodb://127.0.0.1:27017//")
mydb=client["first_database"]
How to create collection and insert document in mongodb using python?
client=pymongo.MongoClient("mongodb://127.0.0.1:27017//")
mydb=client["first_database"]
c1=mydb.first_collection
record_1={
Books:"Python",Price:500,Type:"Programming",Email:"aaaa@gamil.com"
}
c1.insertOne(record_1)
record_2=[
{Books:"Python",Price:500,Type:"Programming",Email:"aaaa@gamil.com"},
{Books:"Javascript",Price:400,Type:"Programming",Email:"ba@gamil.com"},
{Books:"DS math",Price:300,Type:"Math",Email:"caa@gamil.com"}
]
c1.insert_many(record_2)
How to Read document in mongodb using python?
mydb.find_one()
mydb.find({})
How to get values using condition in mongodb using python?
Example 1: Get all the documents of that collection where we have python.
for i in mydb.find({Books:"Python"}):
print(i)
Example:
Use of in
in works like in operator python.
for i in mydb.find({Books:{"$in":["Python","Javascript"]}}):
print(i)
Example 1: Get values where Books is python and Price is less than 300
for i in mydb.find({Books:"Python",Price:{"$lt":300}}):
print(i)
Use of or
or works like or operator in python .
Example 1:Get documents where Books value is python or Type is programming
for i in mydb.find({"%or":[{Books:"Python"},{Type:"Programming"}]}):
print(i)
Use of and
and works like and operator in python .
Example: Get documents where Books value is python and Price is 300
for i in mydb.find({"%and":[{Books:"Python"},{Price:300}]}):
print(i)
How to update records or documents in mongodb using python?
mydb.update_one(
{Price:300},{"$set":{Books:"DT",Type:"Science"}} )
mydb.update_many(
{Price:300},{"$set":{Books:"DT",Type:"Science"}}, {Type:"Programming"},{"$set":{Books:"P-books",Type:"P"}} )