How to connect Python to MongoDB?¶
The pymongo library connects to a Mongo database server. It is capable of interacting with both local and remote databases. To connect to a local instance, no extra parameters are necessary.
Install it with:
pip install pymongo
Launch MongoDB through docker¶
To try MongoDB, it is best to launch it in a local docker container:
docker run -d -p 27017:27017 mongo
Run queries¶
The following code connects and runs a few queries:
import pymongo
client = pymongo.MongoClient("localhost", 27017) # not necessary on localhost
db = client.test
print(db.name)
print(db.my_collection)
db.my_collection.insert_one({"x": 10})
db.my_collection.insert_many([
{"pi": 3.1415},
{"answer_to_everything": 42},
])
db.my_collection.insert_one({"x": 11})
# get one entry
print(db.my_collection.find_one())
# iterate over entries
for item in db.my_collection.find():
print(item["x"])
# accelerate query with an index
db.my_collection.create_index("x")
# sort results
for item in db.my_collection.find().sort("x", pymongo.ASCENDING):
print(item["x"])
# chain multiple functions
print([item["x"] for item in db.my_collection.find().limit(2).skip(1)])
See also