Mongoengine 简明教程
MongoEngine - Querying Database
connect() 函数返回 MongoClient 对象。使用此对象提供的 list_database_names() 方法,我们可以检索服务器上的数据库数。
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)
还可以使用 list_collection_names() 方法获取数据库中的集合列表。
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)
如前所述,Document 类具有 objects 属性,该属性允许访问与数据库相关的对象。
As mentioned earlier, the Document class has objects attribute that enable access to objects associated with the database.
newdb 数据库有一个与下面的 Document 类相对应的 products 集合。若要获取所有文档,我们按如下所示使用 objects 属性:
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)