MongoEngine – Querying Database

MongoEngine – Querying Database

The connect() function returns a MongoClient object. Using list_database_names() method available to this object, we can retrieve number of databases on the server.

from mongoengine import *
con=connect('newdb')
dbs=con.list_database_names()
for db in dbs:
print (db)

It is also possible to obtain list of collections in a database, using list_collection_names() method.

collections=con['newdb'].list_collection_names()
for collection in collections:
print (collection)

As mentioned earlier, the Document class has objects attribute that enable access to objects associated with the database.
The newdb database has a products collection corresponding to Document class below. To get all documents, we use objects attribute as follows −

from mongoengine import connect
from mongoengine import StringField, IntField, Document, DecimalField
connect('mydata', host='mongodb://localhost/mydata')
class Books(Document):
book_id = IntField(unique=True, required=True)
book_name = StringField(max_length=50)
book_price = DecimalField()
def _init__(self, book_id, book_name, book_price):
self.book_id = book_id
self.book_name = book_name
self.book_price = book_price
for book in Books.objects:
print('ID:', book.book_id, 'Name:',
book.book_name, 'Price:', book.book_price)

Output

ID: 1001 Name: let us C Price: 360.00
ID: 1002 Name: Cyber Security Price: 450.00
ID: 1003 Name: Machine Learning Price: 1000.00
ID: 1004 Name: Data Structure Price: 1300.00
MongoEngine – Dynamic Schema (Prev Lesson)
(Next Lesson) MongoEngine – Filters