from pymongo import MongoClient
# Connect to the local MongoDB server
client = MongoClient('localhost', 27017)
# Select the 'planetmars' database
db = client['planetmars']
# Choose the collection
collection = db['mycollection']
# Insert a single document
result = collection.insert_one({'name': 'John', 'age': 30})
# Insert multiple documents
documents = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 35}]
result = collection.insert_many(documents)
# Print the inserted document's _id
print(result.inserted_id)
from pymongo import MongoClient
# Connect to the local MongoDB server
client = MongoClient('localhost', 27017)
# Select the 'planetmars' database
db = client['planetmars']
# Choose the collection 'my_collection'
collection = db['my_collection']
# Now you can use the 'collection' object to perform operations on the collection
# For example, you can insert a document
result = collection.insert_one({'name': 'John', 'age': 30})
# Print the result
print(result)
# You can also check if the collection exists
if 'my_collection' in db.list_collection_names():
print("'my_collection' exists.")
else:
print("'my_collection' does not exist or has not been initialized with any data.")