Python MongoDB - insert_one Query

Python MongoDB - insert_one Query

To insert a document into a MongoDB collection using Python, you can utilize the insert_one() method provided by the PyMongo library.

Here's a step-by-step guide to using insert_one() with MongoDB in Python:

1. Installation:

If you haven't already installed the PyMongo library, you can do so using pip:

pip install pymongo 

2. Establish Connection:

Connect to the MongoDB server. Usually, the MongoDB server runs on localhost at port 27017 unless you've configured it differently.

from pymongo import MongoClient # Connect to the MongoDB server running on localhost at default port 27017 client = MongoClient('localhost', 27017) 

3. Access Database and Collection:

Specify the database and collection where you wish to insert the document. If the database or collection doesn't already exist, it will be created.

# Use a database named 'mydatabase' db = client['mydatabase'] # Use a collection named 'mycollection' collection = db['mycollection'] 

4. Insert a Document:

To insert a single document into the collection, use the insert_one() method.

# Sample document to insert document = { "name": "John", "age": 25, "city": "New York" } # Insert the document into the collection result = collection.insert_one(document) # Print the _id of the inserted document print("Inserted document _id:", result.inserted_id) 

With this approach, if the insert is successful, the _id of the inserted document will be printed. If you don't provide an _id in the document, MongoDB will automatically create one for you.

Remember to handle exceptions and potential errors (e.g., connection failures, duplicate _id values) in a production setting.


More Tags

deep-learning package-managers compare scenarios css-modules spring-mvc youtube-data-api fuzzy-search jquery ruby-hash

More Programming Guides

Other Guides

More Programming Examples