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.

>>> disconnect()
>>> con=connect()
>>> dbs=con.list_database_names()
>>> for db in dbs:
...     print(db)
...
admin
config
local
myDb
sampleDB
test
>>>

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

>>> collections=con["myDb"].list_collection_names()
>>> for collection in collections:
...     print(collection)
...
mycol
sampleCollection
student
>>>

As mentioned earlier, the Document class has objects attribute that enable access to objects associated with the database.

The myDb database has a products collection corresponding to Document class below. To get all documents, we use objects attribute as follows −

main.py

from mongoengine import *

con = connect('myDb')

class Product(Document):
   productID = IntField(required=True)
   name = StringField()
   price = IntField()
   
product_list = [
   Product(productID=1, name="Laptop", price=25000),
   Product(productID=2, name="TV", price=50000),
   Product(productID=3, name="Router", price=2000),
   Product(productID=4, name="Scanner", price=5000),
   Product(productID=5, name="Printer", price=12500),
]   
inserted_products = Product.objects.insert(product_list) 

print(f"Inserted {len(inserted_products)} products.")

for product in Product.objects:
   print ('ID:',product.productID, 'Name:',product.name, 'Price:',product.price)

Output

Compile and run the above code and verify the output −

Inserted 5 products.
ID: 1 Name: Laptop Price: 25000
ID: 2 Name: TV Price: 50000
ID: 3 Name: Router Price: 2000
ID: 4 Name: Scanner Price: 5000
ID: 5 Name: Printer Price: 12500
Advertisements