Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between EmbeddedDocumentField and ReferenceField in mongoengine

Internally, what are the differences between these two fields? What kind of schema do these fields map to in mongo? Also, how should documents with relations be added to these fields? For example, if I use

from mongoengine import *

class User(Document):
    name = StringField()

class Comment(EmbeddedDocument):
    text = StringField()
    tag  = StringField()

class Post(Document):
    title    = StringField()
    author   = ReferenceField(User)
    comments = ListField(EmbeddedDocumentField(Comment)) 

and call

>>> some_author = User.objects.get(name="ExampleUserName")
>>> post = Post.objects.get(author=some_author)
>>> post.comments
[]
>>> comment = Comment(text="cool post", tag="django")
>>> comment.save()
>>> 

should I use post.comments.append(comment) or post.comments += comment for appending this document? My original question stems from this confusion as to how I should handle this.

like image 325
user1876508 Avatar asked Jul 03 '13 17:07

user1876508


People also ask

Which is better PyMongo or MongoEngine?

Both PyMongo and MongoEngine can be used to access data from a MongoDB database. However, they work in very different ways and offer different features. PyMongo is the MongoDB recommended library. It makes it easy to use MongoDB documents and maps directly to the familiar MongoDB Query Language.

What is document in MongoEngine?

MongoEngine defines a Document class. This is a base class whose inherited class is used to define structure and properties of collection of documents stored in MongoDB database. Each object of this subclass forms Document in Collection in database.

What is Python MongoEngine?

MongoEngine is a Python library that acts as an Object Document Mapper with MongoDB, a NOSQL database. It is similar to SQLAlchemy, which is the Object Relation Mapper (ORM) for SQL based databases.

How do I update MongoEngine?

MongoEngine provides the following methods for atomic updates on a queryset. update_one() − Overwrites or adds first document matched by query. update() − Performs atomic update on fields matched by query. modify() − Update a document and return it.


1 Answers

EmbeddedDocumentField is just path of parent document like DictField and stored in one record with parent document in mongo.

To save EmbeddedDocument just save parent document.

>>> some_author = User.objects.get(name="ExampleUserName")
>>> post = Post.objects.get(author=some_author)
>>> post.comments
[]
>>> comment = Comment(text="cool post", tag="django")
>>> post.comment.append(comment)
>>> post.save()

>>> post.comment
[<Comment object __unicode__>]

>>> Post.objects.get(author=some_author).comment
[<Comment object __unicode__>]

See documentation: http://docs.mongoengine.org/guide/defining-documents.html#embedded-documents.

like image 179
tbicr Avatar answered Oct 19 '22 02:10

tbicr