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>]