Skip to content

Instantly share code, notes, and snippets.

@shekharkoirala
Last active February 2, 2019 06:07
Show Gist options
  • Save shekharkoirala/6f2eaed24729ca01554d6da7bf3ed24c to your computer and use it in GitHub Desktop.
Save shekharkoirala/6f2eaed24729ca01554d6da7bf3ed24c to your computer and use it in GitHub Desktop.
Insert nested json in Mongodb
from pymongo import MongoClient , DESCENDING , ASCENDING
mongo_uri = "mongodb://localhost:27017/"
client = MongoClient(mongo_uri)
db = client['medium_gist']
def create_collection(customer_detail):
post = {"name": customer_detail["name"],
"Address": customer_detail["address"],
"items": {}
}
db.customer_info.insert_one(post)
def buy_item(customer_name,item_name, item_json):
db.customer_info.update_one({"name": customer_name},
{"$set": {"items."+ item_name: item_json}})
# add customers
create_collection(customer_detail = {"name": "CustomerA", "address":"AddressA"})
create_collection(customer_detail = {"name": "CustomerB", "address":"AddressB"})
transaction_detail = [{"name": "CustomerA",
"item": "candy",
"detail": {"Sixlets": 8, "Hersheys": 4}},
{"name": "CustomerA",
"item": "cookie",
"detail": {"Oreo": 2, "Dough not": 10}},
{"name": "CustomerB",
"item": "fruits",
"detail": {"melon":6, "kiwi": 23}
}]
# insert transactions
for each_transaction in transaction_detail:
buy_item(customer_name=each_transaction['name'],
item_name=each_transaction['item'],
item_json=each_transaction['detail'])
#fetch data
def search_item(item_category, item_name=None):
if item_name:
return list(db.customer_info.find({"items."
+ item_category + "."
+ item_name:{"$exists": True}}))
else:
return list(db.customer_info.find({"items."
+ item_category:{"$exists": True}}))
search_item(item_category="fruits", item_name="melon")
search_item(item_category="cookie")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment