Friday, February 17, 2023

Retrieving / Fetching the Data

We can query MongoDB using a dictionary-like notation or the dot operator in PyMongo. In the previous section, we used the dot operator to access the MongoDB database. Here, we will also see a demonstration of a dictionary-like syntax.

First, let’s fetch a single document from the MongoDB collection. We’ll use the find_one function for this purpose:

table.find_one()


We can see that the function has returned a dictionary. Let’s see the keys of this dictionary and then I will explain the purpose of each key.

first_instance.keys()


We can see some of the keys are self-explanatory. Let me explain what each of these keys is storing:

  • _id: MongoDB assigns a unique Id to each document
  • username: It contains the username of the user
  • name: The name of the user
  • address: Address of the user is stored in this field
  • birthdate: This argument stores the Date of Birth of the user
  • email: This is the email id of a given user
  • active: This field tells whether the user is active or not
  • accounts: It stores the list of all the accounts held by a given user. A user can have multiple accounts
  • teir_and_details: The category (silver, gold, etc.) is stored in this argument. This field also stores the benefits they are entitled to

Now, let’s see an example of dictionary-like access for MongoDB. Let’s fetch the name of the customer from the MongoDB document:

first_instance['name']

We can also use the find function to fetch the documents. find_one fetches only one document at a time. On the other hand, find can fetch multiple documents from the MongoDB collection:

table.find().sort("_id",pymongo.DESCENDING)

Here, the sort function sorts the documents in the descending order of _id.

Share:

0 comments:

Post a Comment