MongoDB Python | Insert and Update Data

MongoDB Python | Insert and Update Data

Interacting with MongoDB in Python is typically done using the pymongo library. To insert and update data in MongoDB using pymongo, follow these steps:

1. Installation

First, you need to install the pymongo library. You can do this using pip:

pip install pymongo 

2. Connecting to MongoDB

Before inserting or updating data, you need to establish a connection to your MongoDB server:

from pymongo import MongoClient # Connect to the local MongoDB server client = MongoClient('localhost', 27017) # Connect to a specific database (mydatabase in this case) db = client['mydatabase'] 

3. Inserting Data

Inserting a Single Document

# Connect to a specific collection (mycollection in this case) collection = db['mycollection'] # Create a dictionary to represent a document document = { "name": "John", "age": 28, "city": "New York" } # Insert the document into the collection inserted_id = collection.insert_one(document).inserted_id print(f"Document inserted with id: {inserted_id}") 

Inserting Multiple Documents

documents = [ {"name": "Alice", "age": 25, "city": "Los Angeles"}, {"name": "Bob", "age": 30, "city": "Chicago"} ] # Insert the documents into the collection inserted_ids = collection.insert_many(documents).inserted_ids print(f"Documents inserted with ids: {inserted_ids}") 

4. Updating Data

Updating a Single Document

To update a single document, you can use the update_one method:

# Define the query to match the document to update query = {"name": "John"} # Define the update update = { "$set": { "age": 29 } } # Perform the update result = collection.update_one(query, update) print(f"Matched {result.matched_count} documents and modified {result.modified_count} documents.") 

Updating Multiple Documents

To update multiple documents, use the update_many method:

# Update all documents where city is "New York" to have a new field "state" set to "NY" query = {"city": "New York"} update = { "$set": { "state": "NY" } } result = collection.update_many(query, update) print(f"Matched {result.matched_count} documents and modified {result.modified_count} documents.") 

These are the basic steps to insert and update data in MongoDB using Python's pymongo library. Remember that MongoDB is schema-less, so each document in a collection can have different fields. However, it's generally a good practice to ensure data consistency across your documents.


More Tags

roguelike pull-to-refresh azure-pipelines-yaml manifest.json mysql-5.6 aspose multiline fusioncharts namevaluecollection jwe

More Programming Guides

Other Guides

More Programming Examples