问题
I use mongoengine as Object-Document mapper. Here is a brief description of the collections that are causing the problem. Each document in collection A, can have a list of references to documents in Collection B.
class A(Document):
list_b = ListField(EmbeddedDocumentField(EB))
#other fields are not mentioned.
class EB(EmbeddedDocument):
b_reference = ReferenceField('B')
loc = GeoPointField()
class B(Document):
name = StringField()
#other fields are not mentioned.
When i try to access the list objects of a particular document with
document_of_A.list_b
the execution time of the above line depends on the no.of references present in the list. For eg. it takes 100ms for 100 references in the list.
Is there a better way to fetch the references?, so that the execution time of the above mentioned line is reduced.
回答1:
You should use the select_related
flag when querying if you want to get all the references quickly. Please note reference lookups will cost extra queries and select_related()
is designed to reduce the number of round trips to mongodb.
# Single document lookup
document_of_A.select_related(2)
# Queryset
A.objects.select_related(2)
Why 2 for the select_related lookup? Well the recursive depth is:
- look up any references in the list itself
- looking up references in the individual embedded documents
来源:https://stackoverflow.com/questions/16119422/mongodb-references-fetching-takes-time