Untitled
unknown
plain_text
2 years ago
1.6 kB
11
Indexable
# Open a connection to a MongoDB Atlas cluster using a connection string stored in the environment variable 'CONNECTION_STRING'.
from pymongo import MongoClient
import os
def connect_to_atlas():
try:
client = MongoClient(os.environ['CONNECTION_STRING'])
return client
except Exception as e:
print(e)
return None
if __name__ == '__main__':
client = connect_to_atlas()
if client:
print('Connected to MongoDB Atlas!')
else:
print('Failed to connect to MongoDB Atlas!')
# Insert a new document into the database 'database', collection 'people' with the field 'name' set to the value 'Dominic'.
client.database.people.insert_one({'name': 'Dominic'})
# In the database 'database2', collection 'people', find the document where the field 'name' is set to 'Luce'.
result = client.database2.people.find_one({'name': 'Luce'})
print(result)
# Find all documentts with the field 'name' set to 'John'.
results = client.database2.people.find({'name': 'John'})
# Delete the document where the name field is set to John.
client.database2.people.delete_one({'name': 'John'})
# Push a new value 'foo' into the array 'bars' in all documents.
client.database2.people.update_many({}, {'$push': {'bars': 'foo'}})
# Build an aggregation for the collection 'people'. Match documents with the 'name' being 'John' and project only the 'name' field.
pipeline = [
{'$match': {'name': 'John'}},
{'$project': {'name': 1}}
]
results = client.database2.people.aggregate(pipeline)
Editor is loading...