查询效率mongodb

Query efficiency mongodb

哪个查询效率更高:

for id in user.posts:
    Post.objects.get(id=id)

posts = Post.objects(user=user_id)

使用下一个架构

Post(Document):
    user = ObjectIdField()

User(Document):
    posts = ListField(ObjectIdField())

如果 Post 文档中的 user 字段有索引,并且每个 User 平均有 20 个帖子。也很好奇其他使用模式场景

以下块将触发与 user.posts 中的 post 一样多的数据库查询,因此它无论如何都会很慢。

for id in user.posts:
    Post.objects.get(id=id)

但是如果你这样使用它:

Post.objects.get(id__in=user.posts)

然后性能将类似于使用 Post.objects(user=user_id) 因为默认情况下主键被索引

我相信您也应该使用 ReferenceField i.o 纯 ObjectId。它们允许延迟加载引用

class Post(Document):
    user = ReferenceField("User")

class User(Document):
    name = StringField()

    @property
    def posts(self):
        return Post.objects(user=self)

john = User(name='John').save()
post = Post(user=john).save()

print(john.posts()) # [<Post: Post object>]