Linux

MongoDB Document Find using Python

In the previous chapter, we had inserted the records in the book_collection collection of books database. Now we are going to discuss the code to view the records.

Click to view JSON File
Here is the minimum code named using_find.py to view the records:
MongoDB Document find using Python
MongoDB Document find using Python
Click to view code
I think you are acquainted with the first four lines. Code line cursor = record1.find() tells the cursor to contain all the records. If you print the cursor variable, it will give you addresses like In order to print the cursor document, we have used the for loop. Run the program and you will get the output as shown figure below.
MongoDB Document find
MongoDB Document find
Above figure shows all records, If you wish to find some specific records. For instance, we are interested in ID= 42, let us make some amendments in the code.
Python MongoDB Document find specific field
MongoDB Document find specific field
Click to view code
In line number 7, with in find() function, we specified {"ID":42} and {"ID":True, "_id":False, "record":True}. It means we are interested in records where ID= 42, and display only ID and record fields. If you don't want to print ID field, just remove "ID":True from line 7.
Python MongoDB Document print specific field
MongoDB Document find specific field

Consider a scenario where we want all records, but we wish to display only record fields. Let us check our next code.
MongoDB Document print records specific field
MongoDB Document print records specific field
Click to view code
See the out-put in below figure.
Python MongoDB Document print specific field
MongoDB Document find specific field
Now you got idea, how to view and find the records in Mongodb using Pymongo.






admin