Last active
May 10, 2021 14:50
-
-
Save vipul43/f48fc70bed542f88db378e949f85a118 to your computer and use it in GitHub Desktop.
first experiment with pymongo python client commands
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pip install pymongo -> to install pymongo | |
from pymongo import MongoClient | |
import pprint | |
#creating client, database, collection and inserting one record | |
client = MongoClient() | |
print(client.list_database_names()) #will not be printed here | |
db = client['python_test_db'] | |
collection = db['actors'] | |
actor = { | |
name: 'Robert Downey Jr' | |
} | |
data = collection.insert_one(actor) | |
data_id = data.inserted_id | |
print(data_id) | |
print(db.list_collection_names()) | |
print(client.list_database_names()) #will be printed here | |
#querying | |
print(db.actors.find_one()) | |
pprint.pprint(db.actors.find_one()) #this doesn't work if customised id is used or if the number of attributes is less than two | |
pprint.pprint(db.actors.find_one({"_id":'60993d7c42cddfa5e66bfd2d'})) #this doesn't work, returns None | |
pprint.pprint(db.actors.find_one({"_id":data_id})) #this works | |
#find returns pymongo cursor | |
for d in db.actors.find().sort('name'): | |
pprint.pprint(d) | |
#or | |
for d in collection.find().sort('name'): | |
pprint.pprint(d) | |
#filtering | |
db.actors.count_documents({"name":"Robert Downey Jr"}) | |
#updating | |
db.actors.update_many({"name": {"$regex": "^Robert"}}, {"$set": {"name": "Steve Rogers"}}) | |
#or | |
collection.update_many({"name": {"$regex": "^Robert"}}, {"$set": {"name": "Steve Rogers"}}) | |
#limit | |
for d in db.actors.find().limit(1): | |
pprint.pprint(d) | |
#delete | |
db.actors.delete_one({"name": "Steve Rogers"}) | |
#or | |
collection.delete_one({"name": "Steve Rogers"}) | |
#insertion | |
db = client.agg | |
collection = db.grades | |
docs = [ | |
{'s_id': 1,'c_id': 1,'grades': 10}, | |
{'s_id': 1,'c_id': 2,'grades': 15}, | |
{'s_id': 1,'c_id': 3,'grades': 50}, | |
{'s_id': 2,'c_id': 1,'grades': 40}, | |
{'s_id': 2,'c_id': 2,'grades': 20}, | |
{'s_id': 2,'c_id': 3,'grades': 11}, | |
{'s_id': 3,'c_id': 1,'grades': 16}, | |
{'s_id': 3,'c_id': 2,'grades': 18}, | |
{'s_id': 3,'c_id': 3,'grades': 37}, | |
{'s_id': 4,'c_id': 1,'grades': 23}, | |
{'s_id': 4,'c_id': 2,'grades': 41}, | |
{'s_id': 4,'c_id': 3,'grades': 53} | |
] | |
db.grades.insert_many(docs) | |
#aggregation | |
for doc in db.grades.aggregate([{"$group":{"_id":"$s_id","total":{"$sum":"$grades"}}},{"$sort":{"_id":pymongo.ASCENDING}},{"$limit":2}]): | |
pprint.pprint(doc) | |
print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment