couldn't dispaly results using format in pymongo

Viewed 39

I'm working with jupyter notebook, pymongo. and I'm trying to display my results using format.

Here's an example of my collection user

"_id": {
    "$oid": "61bd0b558659f89f7e5b1c56"
  },
  "first_name": "Brandise",
  "last_name": "Ingerman",
  "email": "bingerman0@youku.com",
  "gender": "Female",
  "address": {
    "city": "Fresno",
    "state": "California",
    "country": "United States",
    "country_code": "US"
  },
  "card": {
    "card_number": "3571237735836521",
    "card_type": "jcb",
    "currency_code": "USD",
    "balance": 630.16
  },
  "married_status": "true"

and here's the query that I'm executing

pipeline = [
   {
      "$match":{
         "card.card_type": "jcb"
      }
   },
   {
      "$sort":{
         "card.balance":-1
      }
   }
]
results = users.aggregate(pipeline)
for user in results:
   print(" * user name: {first_name}, card number: {card_number}, balance: {balance}".format(
         first_name=user["first_name"],
         card_number=user["card.card_number"],
         balance=user["card.balance"],
   ))

It says

     15    print(" * user name: {first_name}, card number: {card_number}, balance: {balance}".format(
     16          first_name=user["first_name"],
---> 17          card_number=user["card.card_number"],
     18          balance=user["card.balance"],
     19    ))

KeyError: 'card.card_number'

I've tried calling card_number but it keeps prompting errors, couldn't figure out how.

3 Answers
card_number=user["card"]["card_number"]
balance=user["card"]["balance"]

This should work. MongoDB docs which are returned should be in nested dictionary format. So, you need to access the keys for the inner dictionaries step-by-step. It's also recommended that you convert the data fetched from mongo into a python list. This makes things easier in the long run.

Does your collection contain an entry where the card.card_number key does not exist?

Try running this query to see if there are any:

users.find({"card.card_number": {$exists: False}})

pipeline = [
   {
      "$match":{
         "card.card_type": "jcb"
      }
   },
   {
      "$sort":{
         "card.balance":-1
      }
   }
]
results = users.aggregate(pipeline)
for user in results:
   print(" * user name: {first_name}, card number: {card_number}, balance: {balance}".format(
         first_name=user["first_name"],
         card_number=user["card"]["card_number"],
         balance=user["card"]["balance"],
   ))
Related