To insert a document (which is equivalent to a row in a relational database) into a MongoDB collection using Python and the "pymongo" library.
we can use the "insert_one()" or "insert_many()" methods.
Here's how we can insert document into a MongoDB collection:
After importing "pymongo", we must provide a connection URL and database name to MongoClient.
# import pymongo library import pymongo # Connection URL and database name uri = "mongodb://localhost:27017/" database_name = "your_database_name" collection_name = "your_collection_name" # Connect to MongoDB server client = pymongo.MongoClient(uri) # Access the database db = client[database_name] # Access the collection collection = db[collection_name]
Replace "mongodb://localhost:27017/" with the connection string for your MongoDB server.
Replace "your_database_name" with the name of the database where the collection exists or where you want to insert the document.
Replace "your_collection_name" with the name of the collection where you want to insert the document.
# Document to insert document = {"name": "Alice", "age": 20} # Insert the document into the collection insert_result = collection.insert_one(document) # Print the inserted document's ID print("Inserted document ID:", insert_result.inserted_id)
The "insert_one()" method is used to insert a single document into the collection. We can pass the document (in the form of a dictionary) as an argument to this method.
The "inserted_id" attribute of the "insert_result" object contains the "_id" of the inserted document. You can use this "ID" to retrieve the inserted document later if needed.
# insert Multiple Document at once documents = [ {"name": "Alice", "age": 25}, {"name": "Edward", "age": 26}, {"name": "Charles", "age": 45} ] # Insert the documents into the collection insert_result = collection.insert_many(documents) # Print the IDs of the inserted documents print("Inserted document IDs:", insert_result.inserted_ids)
we can insert multiple documents at once, we can use the "insert_many()" method.
This will insert multiple documents into the collection at once.
The "inserted_ids" attribute of the "insert_result" object contains a list of the "_id" values of the inserted documents.