How to Use MongoDB in Python

Install MongoDB Community Server

MongoDB is a NoSQL database product. MongoDB uses collections to organize documents, and each document is composed of key-value pairs.

More information about MongoDB: https://en.wikipedia.org/wiki/MongoDB

Download and install Mongo from here: Download MongoDB Community Server | MongoDB

After the installation is complete, add the directory of the bin folder in the MongoDB folder (such as C:\MongoDB\bin) to the environment variable.


Start MongoDB Community Server

Enter the following code in cmd to start MongoDB:

1
mongod --dbpath your_path\MongoDB\data

Note: Replace the above installation path with your own, such as: D:\software\MongoDB\data.

Then you can see this:

If you enter http://localhost:27017/ in your browser, you will see the following information:

Now that you have successfully started MongoDB server, don't close the cmd window, otherwise the MongoDB server will also exit. If your local MongoDB server is started, you can also see it in the task manager:

Next, let's try to use MongoDB in Python.


Use MongoDB in Python

Install pymongo library in Python:

1
pip install pymongo

Connect and initialize the local MongoDB server:

1
2
3
4
5
6
7
8
9
10
from pymongo import MongoClient

# Connect to a local MongoDB instance
client = MongoClient('localhost', 27017)

# Select the database, if the database does not exist, MongoDB will automatically create it when the data is inserted for the first time
db = client['test_database']

# Select Collections, if the collection doesn't exist, MongoDB will automatically create it when you first insert a document
collection = db['test_collection']

Commonly used functions of pymongo library are as follows:

insert_one()

1
2
3
4
5
6
7
8
9
10
11
# Insert a single document
post = {"name": "A",
"age": 20,
"score": [80, 82, 90]}
post_id = collection.insert_one(post).inserted_id
print("Post ID:", post_id)
print("The files in the collection are as follows:")
# Get and print all the documents in the collection
documents = collection.find()
for document in documents:
print(document)

The output is as follows:

1
2
3
Post ID: 669a22d3cecfcecf696ee9e9
The files in the collection are as follows:
{'_id': ObjectId('669a22d3cecfcecf696ee9e9'), 'name': 'A', 'age': 20, 'score': [80, 82, 90]}

insert_many()

1
2
3
4
5
6
7
8
9
10
11
12
# Insert multiple documents
posts = [{"name": "B", "age": 21, "score": [75, 80, 96]},
{"name": "B", "age": 21, "score": [100, 100, 100]},
{"name": "C", "age": 20, "score": [86, 95, 80]}]
result = collection.insert_many(posts)

print("Inserted post IDs:", result.inserted_ids)
print("The files in the collection are as follows:")
# Get and print all the documents in the collection
documents = collection.find()
for document in documents:
print(document)

The output is as follows:

1
2
3
4
5
6
Inserted post IDs: [ObjectId('669a22d3cecfcecf696ee9ea'), ObjectId('669a22d3cecfcecf696ee9eb'), ObjectId('669a22d3cecfcecf696ee9ec')]
The files in the collection are as follows:
{'_id': ObjectId('669a22d3cecfcecf696ee9e9'), 'name': 'A', 'age': 20, 'score': [80, 82, 90]}
{'_id': ObjectId('669a22d3cecfcecf696ee9ea'), 'name': 'B', 'age': 21, 'score': [75, 80, 96]}
{'_id': ObjectId('669a22d3cecfcecf696ee9eb'), 'name': 'B', 'age': 21, 'score': [100, 100, 100]}
{'_id': ObjectId('669a22d3cecfcecf696ee9ec'), 'name': 'C', 'age': 20, 'score': [86, 95, 80]}

find_one()

1
2
3
4
# Query a single document
post = collection.find_one({"score": [80, 82, 90]})
print("Query results:")
print(post)

The output is as follows:

1
2
Query results:
{'_id': ObjectId('669a22d3cecfcecf696ee9e9'), 'name': 'A', 'age': 20, 'score': [80, 82, 90]}

find()

1
2
3
4
# Query multiple documents
print("Query results:")
for post in collection.find({"name": "B"}):
print(post)

The output is as follows:

1
2
3
Query results:
{'_id': ObjectId('669a22d3cecfcecf696ee9ea'), 'name': 'B', 'age': 21, 'score': [75, 80, 96]}
{'_id': ObjectId('669a22d3cecfcecf696ee9eb'), 'name': 'B', 'age': 21, 'score': [100, 100, 100]}

update_one()

1
2
3
4
5
6
7
8
9
10
11
# Update a single document
collection.update_one(
{"name": "A"},
{"$set": {"name": "new_A", "score": [100, 100, 100]}}
)

print("The files in the collection are as follows:")
# Get and print all the documents in the collection
documents = collection.find()
for document in documents:
print(document)

The output is as follows:

1
2
3
4
5
The files in the collection are as follows:
{'_id': ObjectId('669a22d3cecfcecf696ee9e9'), 'name': 'new_A', 'age': 20, 'score': [100, 100, 100]}
{'_id': ObjectId('669a22d3cecfcecf696ee9ea'), 'name': 'B', 'age': 21, 'score': [75, 80, 96]}
{'_id': ObjectId('669a22d3cecfcecf696ee9eb'), 'name': 'B', 'age': 21, 'score': [100, 100, 100]}
{'_id': ObjectId('669a22d3cecfcecf696ee9ec'), 'name': 'C', 'age': 20, 'score': [86, 95, 80]}

update_many()

1
2
3
4
5
6
7
8
9
10
11
# Update multiple documents
collection.update_many(
{"age": 20},
{"$set": {"status": "Graduated"}}
)

print("The files in the collection are as follows:")
# Get and print all the documents in the collection
documents = collection.find()
for document in documents:
print(document)

The output is as follows:

1
2
3
4
5
The files in the collection are as follows:
{'_id': ObjectId('669a22d3cecfcecf696ee9e9'), 'name': 'new_A', 'age': 20, 'score': [100, 100, 100], 'status': 'Graduated'}
{'_id': ObjectId('669a22d3cecfcecf696ee9ea'), 'name': 'B', 'age': 21, 'score': [75, 80, 96]}
{'_id': ObjectId('669a22d3cecfcecf696ee9eb'), 'name': 'B', 'age': 21, 'score': [100, 100, 100]}
{'_id': ObjectId('669a22d3cecfcecf696ee9ec'), 'name': 'C', 'age': 20, 'score': [86, 95, 80], 'status': 'Graduated'}

delete_one()

1
2
3
4
5
6
7
8
# Delete a single documents
collection.delete_one({"name": "B", "score": [100, 100, 100]})

print("The files in the collection are as follows:")
# Get and print all the documents in the collection
documents = collection.find()
for document in documents:
print(document)

The output is as follows:

1
2
3
4
The files in the collection are as follows:
{'_id': ObjectId('669a22d3cecfcecf696ee9e9'), 'name': 'new_A', 'age': 20, 'score': [100, 100, 100], 'status': 'Graduated'}
{'_id': ObjectId('669a22d3cecfcecf696ee9ea'), 'name': 'B', 'age': 21, 'score': [75, 80, 96]}
{'_id': ObjectId('669a22d3cecfcecf696ee9ec'), 'name': 'C', 'age': 20, 'score': [86, 95, 80], 'status': 'Graduated'}

delete_many()

1
2
3
4
5
6
7
8
# Delete multiple documents
collection.delete_many({"status": "Graduated"})

print("The files in the collection are as follows:")
# Get and print all the documents in the collection
documents = collection.find()
for document in documents:
print(document)

The output is as follows:

1
2
The files in the collection are as follows:
{'_id': ObjectId('669a22d3cecfcecf696ee9ea'), 'name': 'B', 'age': 21, 'score': [75, 80, 96]}

delete all files in the collection:

1
collection.delete_many({})

Additionally, If you want to disconnect from MongoDB server, you can use:

1
2
# Disconnect from MongoDB
client.close()

More information about pymongo: https://pymongo.readthedocs.io/en/stable/