Week5_MongoDB
Week 5 Class Exercise :: MongoDB¶
Copyright By PowCoder代写 加微信 powcoder
#!pip3 install pymongo
from pymongo import MongoClient
client = MongoClient(‘localhost’,27017) ## or MongoClient(“localhost:27”)
db = client.apan5400
Create a collection and Insert a document¶
collection = db.test_collection
import datetime
post = {‘author’: ‘ ‘,
“text”: “What a wonderful world”,
“tags”:[“mongodb”, “python”, “pymongo”],
“date”:datetime.datetime.utcnow()
post_id = collection.insert_one(post).inserted_id
print(‘Our first post id: {0}’.format(post_id))
print(‘Our first post: {0}’.format(post))
Our first post id: 6024ecf1aad559a06949895e
Our first post: {‘author’: ‘ ‘, ‘text’: ‘What a wonderful world’, ‘tags’: [‘mongodb’, ‘python’, ‘pymongo’], ‘date’: datetime.datetime(2021, 2, 11, 8, 38, 9, 447072), ‘_id’: ObjectId(‘6024ecf1aad559a06949895e’)}
collection.drop()
Insert multiple JSON documents¶
import json
json_data = open(“webhose_apple.json”).readlines()
newsfeeds = []
for line in json_data:
newsfeeds.append(json.loads(line))
print(len(newsfeeds))
collection = db.webhose_apple
collection.insert_many(newsfeeds)
MongoDB Queries¶
Find a random document¶
#from pprint import pprint
#pprint(collection.find_one())
Count documents in the collection¶
total_docs = collection.count_documents({})
total_docs
Retrieve and count documents based on regular expression query¶
“title”: {
“$regex”: ‘ ‘,
“$options” :’i’ # case-insensitive
results = collection.find(query)
print(collection.count_documents(query))
#for item in results:
# print(item[‘title’])
Drop the collection to clean up¶
print(“before dropping collection:”, collection.count_documents({}))
collection.drop()
print(“after dropping collection:”, collection.count_documents({}))
db.test_collection.drop()
before dropping collection: 10800
after dropping collection: 0
Example with resume processing¶
Insert many job applicants¶
collection = db.resumes
mylist = [
{ “name”: “John”, “city”: ” “, “experience”: 15, “bio”: “data analyst with 15 years of experience”, “prev_salary”: 120000 },
{ “name”: “Wen”, “city”: “San Francisco”, “experience”: 2, “bio”: “medical researcher with MongoDB training”, “prev_salary”: 65000},
{ “name”: “Sophia”,”city”: “Jersey City”, “experience”: 10, “bio”: “business executive with MongoDB expertise”, “prev_salary”: 95000},
{ “name”: “Kelly”, “city”: “Brooklyn”, “experience”: 10, “bio”: “social worker with MongoDB and Postgres knowledge”, “prev_salary”: 87000}
collection.insert_many(mylist)
Sort the applicants by experience¶
for x in collection.find(sort=[(“experience”, -1)]):
{‘_id’: ObjectId(‘6024eea0aad559a06949b393’), ‘name’: ‘Sam’, ‘city’: ‘Los Angeles’, ‘experience’: 15, ‘bio’: ‘data analyst with 15 years of experience’, ‘prev_salary’: 100000}
{‘_id’: ObjectId(‘6024eea0aad559a06949b395’), ‘name’: ‘Sophia’, ‘city’: ‘Jersey City’, ‘experience’: 10, ‘bio’: ‘business executive with MongoDB expertise’, ‘prev_salary’: 100000}
{‘_id’: ObjectId(‘6024eea0aad559a06949b396’), ‘name’: ‘Kelly’, ‘city’: ‘Brooklyn’, ‘experience’: 10, ‘bio’: ‘social worker with MongoDB and Postgres knowledge’, ‘prev_salary’: 87000}
{‘_id’: ObjectId(‘6024eea0aad559a06949b394’), ‘name’: ‘Wen’, ‘city’: ‘San Francisco’, ‘experience’: 2, ‘bio’: ‘medical researcher with MongoDB training’, ‘prev_salary’: 65000}
Update record for the applicant(s)¶
myquery = { “name”: “John” }
newvalues = { “$set”: { “name”: “Sam” } }
collection.update_one(myquery, newvalues)
myquery = { “name”: { “$regex”: “^S” } }
newvalues = { “$set”: { “prev_salary”: 100000 } }
x = collection.update_many(myquery, newvalues)
print(x.modified_count, “documents updated.”)
2 documents updated.
Find the applicant with the most experience with MongoDB¶
“$regex”: ‘MongoDB’,
“$options” :’i’ # case-insensitive
collection.find_one(query, sort=[(“experience”, -1), (“prev_salary”, 1)])
{‘_id’: ObjectId(‘6024ea707c34dff8a595e7a2’),
‘name’: ‘Kelly’,
‘city’: ‘Brooklyn’,
‘experience’: 10,
‘bio’: ‘social worker with MongoDB and Postgres knowledge’,
‘prev_salary’: 87000}
What is the name of the person who lives in Brooklyn¶
print(collection.find_one({“city”: “Brooklyn”}, {“name”:1, “_id”:0}))
print(collection.find_one({“city”: “Brooklyn”})[“name”])
{‘name’: ‘Kelly’}
someone with Postgres and MongoDB experience¶
{“bio”: {“$regex”: “Postgres”}},
{“bio”: {“$regex”: “MongoDB”}}
collection.find_one(query)
{‘_id’: ObjectId(‘6024ea707c34dff8a595e7a2’),
‘name’: ‘Kelly’,
‘city’: ‘Brooklyn’,
‘experience’: 10,
‘bio’: ‘social worker with MongoDB and Postgres knowledge’,
‘prev_salary’: 87000}
#### Drop resumes collection
collection.drop()
Close the connection¶
client.close()
Resource: https://api.mongodb.com/python/current/tutorial.html¶
Resource: https://www.w3schools.com/python/python_mongodb_getstarted.asp¶
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com