Home > Back-end >  Get a specific value from JSON data using MongoDB python
Get a specific value from JSON data using MongoDB python

Time:12-04

I am trying to get a specific value from a nested JSON object. I've tried the following but in all cases I get all the specific values from all the nested objects. I would like to get the specific price from one artist in this case with the id: 1176704.

collection_name = dbname["Tattooparlor"]

cus_details = collection_name.aggregate([{"$match": {"artists._id": 1176704}}])
print(cus_details)

for r in cus_details:
   print(r)

or

for r in collection_name.find({"_id": 9392991}, {"artists._id": 1176704}):
   print(r)
   for x in r["artists"]:
       print(x["price"])

In all cases it returns 1779, 2730, 4530 or the full object and I just want it to return 1779.

My JSON object looks like this

JSON object

CodePudding user response:

if you try by limiting only price field collection_name.find({"_id": 9392991}, {"artists._id": 1176704},{price:1})

CodePudding user response:

Did you try this? You have to find the artist's id then print out his/her price.

for result in collection_name.find({"_id": 9392991}):
    for arr in r["artists"]:
       if arr["_id"] == 1176704:
          print(arr["price"])
  • Related