mongoDB references fetching takes time

柔情痞子 提交于 2019-12-13 06:26:22

问题


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:

  1. look up any references in the list itself
  2. looking up references in the individual embedded documents


来源:https://stackoverflow.com/questions/16119422/mongodb-references-fetching-takes-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!