MongoEngine possible bug (tested on 0.8.4): the result of distinct() operation on ListField of EmbeddedDocuments is a list of dictionaries rather than list of EmbeddedDocuments as it works in previous versions of library. Here is an example.
from mongoengine import *
class Author(EmbeddedDocument):
name = StringField()
class Book(Document):
title = StringField()
authors = ListField(EmbeddedDocumentField(Author))
def populate():
Book.drop_collection()
mark_twain = Author(name="Mark Twain")
john_tolkien = Author(name="John Ronald Reuel Tolkien")
book = Book(title="Tom Sawyer")
book.authors.append(mark_twain)
book.save()
book = Book(title="The Lord of the Rings")
book.authors.append(john_tolkien)
book.save()
book = Book(title="The Stories")
book.authors.append(mark_twain)
book.authors.append(john_tolkien)
book.save()
if __name__ == "__main__":
connect('test')
populate()
books = Book.objects()
print "\nAll books:"
print "\n".join(map(lambda b: b.title + " by " + " and ".join(map(lambda a: a.name, b.authors)), books))
print "\nUnique authors (unexpected output):"
authors = books.distinct("authors")
for author in authors:
print author["name"] + " (" + author.__class__.__name__ + ")"
print "\nUnique authors (expected output):"
authors = map(lambda a: Author(**a), authors)
for author in authors:
print author.name + " (" + author.__class__.__name__ + ")"
The output:
All books:
Tom Sawyer by Mark Twain
The Lord of the Rings by John Ronald Reuel Tolkien
The Stories by Mark Twain and John Ronald Reuel Tolkien
Unique authors (unexpected output):
Mark Twain (BaseDict)
John Ronald Reuel Tolkien (BaseDict)
Unique authors (expected output):
Mark Twain (Author)
John Ronald Reuel Tolkien (Author)
MongoEngine possible bug (tested on 0.8.4): the result of distinct() operation on ListField of EmbeddedDocuments is a list of dictionaries rather than list of EmbeddedDocuments as it works in previous versions of library. Here is an example.
The output: