Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python mongodb的查询效率_Python_Mongodb_Mongodb Query_Mongoengine - Fatal编程技术网

Python mongodb的查询效率

Python mongodb的查询效率,python,mongodb,mongodb-query,mongoengine,Python,Mongodb,Mongodb Query,Mongoengine,哪种查询效率更高: for id in user.posts: Post.objects.get(id=id) 或 使用下一个模式 Post(Document): user = ObjectIdField() User(Document): posts = ListField(ObjectIdField()) 如果在Post文档中有user字段的索引,并且每个用户的Post平均为20。对其他使用模式场景也很好奇下面的代码块触发的数据库查询数量与您在user.post

哪种查询效率更高:

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

使用下一个模式

Post(Document):
    user = ObjectIdField()

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

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

下面的代码块触发的数据库查询数量与您在
user.posts中发布的数据库查询数量相同,因此无论如何都会很慢

for id in user.posts:
    Post.objects.get(id=id)
但是如果你这样使用它:

Post.objects.get(id__in=user.posts)
然后性能将类似于使用
Post.objects(user=user\u id)
,因为默认情况下主键会被索引

我认为您还应该使用ReferenceField I.o plain 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>]
class Post(文档):
用户=引用字段(“用户”)
类用户(文档):
name=StringField()
@财产
def员额(自我):
返回Post.objects(用户=self)
john=User(name='john').save()
post=post(user=john).save()
打印(john.posts())#[]

由于使用索引,第二个可能会更快。
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>]