Using MongoEngine2 in Python

Source: Internet
Author: User

Mongoengine Basic Usage Examples:
 fromMongoengineImport* fromDatetimeImportdatetime#Connection database: Test#Connect (' Test ') # connects to local test databaseConnect'Test', host='127.0.0.1', port=27017, Username='Test', password='Test')#Defining our Documents#define document USER,POST, corresponding set User,postclassUser (Document):#required is true, the initial value must be givenemail = Stringfield (required=True) first_name= Stringfield (max_length=50) last_name= Stringfield (max_length=50) Date= Datetimefield (Default=datetime.now (), required=True)#Embedded Documents,it doesn ' t has its own collection in the databaseclassComment (embeddeddocument): Content=Stringfield () name= Stringfield (max_length=120)classPost (Document): Title= Stringfield (max_length=120, required=True)#Referencefield equivalent to foreign keyAuthor =Referencefield (User) tags= ListField (Stringfield (max_length=30)) Comments=ListField (Embeddeddocumentfield (Comment))#Allow inheritanceMeta = {'allow_inheritance': True}classTextpost (Post): Content=Stringfield ()classImagepost (Post): Image_path=Stringfield ()classLinkpost (Post): Link_url=Stringfield ()#Dynamic Document Schemas:dynamicdocument documents work in the same-as document but any data/attributes set to Them'll also be savedclassPage (dynamicdocument): Title= Stringfield (max_length=200, required=True) date_modified= Datetimefield (Default=datetime.now ())

Add data
John = User (email='[email protected]', first_name='John', last_name='Tao'). Save () Ross= User (email='[email protected]') Ross.first_name='Ross'Ross.last_name='Lawley'ross.save () comment1= Comment (content='Good work!', name ='Lindentao') Comment2= Comment (content='Nice article!') Post0= Post (title ='post0', tags = ['Post_0_tag']) post0.comments=[Comment1,comment2]post0.save () Post1= Textpost (title='Fun with Mongoengine', author=John) Post1.content='Took A look at mongoengine today, looks pretty cool.'Post1.tags= ['MongoDB','Mongoengine']post1.save () post2= Linkpost (title='Mongoengine Documentation', author=Ross) Post2.link_url='http://docs.mongoengine.com/'Post2.tags= ['Mongoengine']post2.save ()#Create A new page and add tagspage = page (title='Using Mongoengine') Page.tags= ['MongoDB','Mongoengine']page.save ()

Three collections created: User,post,page

View data
#View Data forPostinchpost.objects:PrintPost.titlePrint '='*Len (post.title)ifisinstance (Post, textpost):Printpost.contentifisinstance (Post, linkpost):Print 'Link:', Post.link_url#get a reference Document object directly from a reference field forPostinchtextpost.objects:Printpost.contentPrintpost.author.email au=TextPost.objects.all (). First (). AuthorPrintAu.email#Querying by Tags forPostinchPost.objects (tags='MongoDB'):    PrintPost.title num_posts= Post.objects (tags='MongoDB'). Count ()Print 'Found%d posts with tag "MongoDB"'%num_posts#Multi-Criteria Query (Import Q Class)User.objects ((Q (country='UK') & Q (age__gte=18)) | Q (age__gte=20))   #Update documentRoss = user.objects (first_name ='Ross') ross.update (date=DateTime.Now ()) User.objects (first_name='John'). Update (set__email='[email protected]')//Add product picture information to Lorem lorempic= Goodspic (name='l2.jpg', path='/static/images/l2.jpg') Lorem= Goods.objects (id='575d38e336dc6a55d048f35f') Lorem.update_one (Push__pic=lorempic)#Delete a documentRoss.delete ()

Note

ORM Full Name "Object Relational Mapping", that is, object-relational mapping, is to map a row of the relational database to an object, that is, a class corresponding to a table, so that the code is simpler to write, do not directly manipulate the SQL statement.

Using MongoEngine2 in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.