English 中文(简体)
MongoEngine - Querying Database
  • 时间:2024-09-17

MongoEngine - Querying Database


Previous Page Next Page  

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


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

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


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

As mentioned earper, 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 *
con=connect( newdb )
class products (Document):
ProductID=IntField(required=True)
Name=StringField()
price=IntField()
for product in products.objects:
print ( ID: ,product.ProductID,  Name: ,product.Name,  Price: ,product.price)

Output


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