11

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.

4

2 回答 2

10

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.

于 2013-07-04T06:01:20.850 回答
0

This one just a sample case where we can use embedded docs.

Lets say for example you are going to create an app that takes in requirements as they come in and save them in the db. Now your requirement is to assign this requirement to a bunch of people each at a later stage after some processing of the requirement.

you also need to track the changes and log the activity pertaining to the processing taken place with regards to the requirement.

I know i know you might say we can use rdbms kind of relationship with refference field. but it involves in taking care of deleting obselete records in either collections which is nothing but extra code to handle the maintenance of the child collection in case of parent doc being deleted.( There are other extra efforts too that come into place ..)

instead embedded documents are stored as part of the parent doc. which Maintaining parent will involve embedded docs too.

and it will be easy to create complex json structured data using embedded docs rather than using user logic to manipulate and process the data into a complex structure.

Now Here the relation is one requirement to many handlers(which is nothing but an activity log by the handlers for the one requirement).

于 2016-02-15T12:59:03.557 回答