Python MongoDB

🐍 Python MongoDB

In Python MongoDB is a NoSQL database that stores data in JSON-like documents.
It can interact with MongoDB using the pymongo library.


 1️⃣ Install PyMongo

pip install pymongo

 2️⃣ Connect to MongoDB


 

Replace localhost:27017 if you have a remote MongoDB server.


 3️⃣ Create a Collection

Collections are like tables in SQL.


 4️⃣ Insert Documents


students_col.insert_many(students)print(“✅ Documents inserted”)


 5️⃣ Read Documents


 


 6️⃣ Update Documents


 


 7️⃣ Delete Documents


 


 8️⃣ Query Operators

OperatorDescriptionExample
$ltLess than{"age": {"$lt": 25}}
$gtGreater than{"age": {"$gt": 20}}
$lteLess than or equal{"age": {"$lte": 25}}
$gteGreater than or equal{"age": {"$gte": 20}}
$neNot equal{"name": {"$ne": "Vipul"}}
$inIn list{"age": {"$in": [22,24]}}
$ninNot in list{"age": {"$nin": [22,24]}}

 9️⃣ Sorting and Limiting


 


 10️⃣ Drop Collection or Database


 


 11️⃣ Full Example: CRUD in MongoDB


 


MongoDB Advantages:

  • Schema-less, flexible data

  • Stores complex JSON-like documents

  • Fast for reads/writes

  • Easy integration with Python via pymongo

You may also like...