mongoengine教程(2)文档模式
在MongoDB中一个文档(document)与关系型数据库中的一行(row)相似;文档保存在集合(collection)中,行保存在表(table)中。 定义文档的模式 与django类似,要定义一个文档模式只需要创建一个类继承自 Document,并添加一些 Field 对象。 from mongoengine impo
在MongoDB中一个文档(document)与关系型数据库中的一行(row)相似;文档保存在集合(collection)中,行保存在表(table)中。
定义文档的模式
与django类似,要定义一个文档模式只需要创建一个类继承自 Document,并添加一些 Field 对象。
from mongoengine import * import datetime class Page(Document): title = StringField(max_length=200, required=True) date_modified = DateTimeField(default=datetime.datetime.now)
如上定义了一个文档模式具有 title和date_modified 两个字段。
同时MongoDB本身就是无模式的,因此我们还可以创建动态的文档模式。它可以在添加数据时为不同的数据设置不同的字段。
class Page(DynamicDocument): title = StringField(max_length=200, required=True)
添加数据:
page = Page(title='Using MongoEngine') page.tags = ['mongodb', 'mongoengine'] page.save()
文档字段
文档字段(Field)不是必需的,但是使用它来进行数据验证、设置默认值等操作会比较方便。
MongoEngine提供了如下这些类型的Field:
- BinaryField
- BooleanField
- ComplexDateTimeField
- DateTimeField
- DecimalField
- DictField
- DynamicField
- EmailField
- EmbeddedDocumentField
- FileField
- FloatField
- GenericEmbeddedDocumentField
- GenericReferenceField
- GeoPointField
- ImageField
- IntField
- ListField
- MapField
- ObjectIdField
- ReferenceField
- SequenceField
- SortedListField
- StringField
- URLField
- UUIDField
文档之间引用关系
在关系型数据库中多个表可以使用外键进行关联。然而MongoDB是无模式的,因此想要达到这样的效果就这能在应用程序中自己手动的进行关联了。
不过还好,使用MongoEngine的ReferenceField可以很方便的实现。
class User(Document): name = StringField() class Page(Document): content = StringField() author = ReferenceField(User) john = User(name="John Smith") john.save() post = Page(content="Test Page") post.author = john post.save()
一对多的关系
对于一对多的关系可以使用ListField来保存一个ReferenceField列表。在进行查询操作是需要传入一个实例对象。
class User(Document): name = StringField() class Page(Document): content = StringField() authors = ListField(ReferenceField(User)) bob = User(name="Bob Jones").save() john = User(name="John Smith").save() Page(content="Test Page", authors=[bob, john]).save() Page(content="Another Page", authors=[john]).save() # Find all pages Bob authored Page.objects(authors__in=[bob])
引用对象的删除操作
MongoDB默认不会检查数据的完整性,因此在删除一个对象是就需要自己手动的处理引用了该对象的其他对象。
同样的MongoEngine也提供了一样的功能。ReferenceField有一个 reverse_delete_rule 参数可以进行设置。它的取值如下:
- mongoengine.DO_NOTHING:默认就是这个值,它不会进行任何操作。
- mongoengine.DENY:如果该对象还被其他对象引用,则拒绝删除。
- mongoengine.NULLIFY:将其他对象对该对象的引用字段设为null。
- mongoengine.CASCADE:将引用了该对象的其他对象也删除掉。
- mongoengine.PULL:移除对该对象的引用。
索引
与django的Model相似,MongoEngine的Document也可以在meta属性中设置索引。
class Page(Document): title = StringField() rating = StringField() meta = { 'indexes': ['title', ('title', '-rating')] }
meta中的indexes可以是一个列表,也可以是一个字典。
原文地址:mongoengine教程(2)——文档模式, 感谢原作者分享。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to master Bootstrap customization and component usage includes: 1. Use CSS variables and Sass preprocessor for style customization; 2. Deeply understand and modify component structure and behavior. Through these methods, a unique user interface can be created to improve the responsiveness and user experience of the website.

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

Huobi to Binance Transfer Guide: Safe and conveniently transfer your crypto assets Many investors use Huobi and Binance at the same time. This article will guide you how to safely transfer crypto assets on Huobi (HTX), such as TRUMP and USDT, to the Binance platform. Binance is popular for its high security, rich currency and trading pairs, and world-leading trading volume. Binance Exchange’s advantages: the world’s number one trading volume, accounting for 50% of the global market; transparent reserve assets are mainly mainstream stablecoins such as Bitcoin, Ethereum and USDT; it has effectively avoided the potential risks of the US SEC and is one of the most stable and reliable exchanges at present. This tutorial will take TRUMP and USDT as examples

This article describes how to build a highly available MongoDB database on a Debian system. We will explore multiple ways to ensure data security and services continue to operate. Key strategy: ReplicaSet: ReplicaSet: Use replicasets to achieve data redundancy and automatic failover. When a master node fails, the replica set will automatically elect a new master node to ensure the continuous availability of the service. Data backup and recovery: Regularly use the mongodump command to backup the database and formulate effective recovery strategies to deal with the risk of data loss. Monitoring and Alarms: Deploy monitoring tools (such as Prometheus, Grafana) to monitor the running status of MongoDB in real time, and

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

Binance C2C Trading Guide: Safe and convenient way to deposit and withdraw money in cryptocurrency. This article will explain the Binance C2C (CustomertoCustomer) trading model in detail, explain its security, characteristics and operation procedures, and provide graphic tutorials to help you easily master the Binance C2C deposit and withdraw money in ease. What is Binance C2C? Binance C2C is a user-to-user cryptocurrency trading service provided by the Binance platform, providing users with convenient cryptocurrency and fiat currency exchange channels. Launched in 2019, the service supports multiple cryptocurrencies and fiat currency transactions through a peer-to-peer trading model, and provides enhanced security and multiple features. Compared with traditional OTC trading, Binance C2C platform authenticates both parties to the transaction and provides complete support.

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

Binance HODL Airdrop Guide: Get Free Tokens with Easily! Binance has launched a new airdrop mechanism - Binance HODL airdrop, which allows you to get a random new coin airdrop by just holding BNB earning products! This article will explain Binance HODL airdrop in detail, including history query, participation steps and risk assessment. What is Binance HODL airdrop? Binance HODL airdrop is a periodic airdrop of new currency, and uses the "backward snapshot" mechanism to calculate the holdings and airdrop rewards of BNB's currency-making products. You only need to hold BNB current or regular currency earning products within a specific time period before the event announcement to receive the new currency rewards from Binance. It should be noted that when you see the airdrop announcement, the opportunity to participate is deadlined because the system has completed the snapshot. Need to participate
