Mongoengine 聚合 $match 主键 (_id) 不工作
Mongoengine aggregate $match primary key (_id) is not working
我正在尝试将聚合与 mongoengine 结合使用。此外,很难找出它是如何工作的(因为文档中没有关于它的任何内容),我取得了一些进展。
但是我无法匹配主键:
from mongoengine import *
connect('test')
class User(Document):
username = StringField()
def match_test_username(self):
pipeline = [{ "$match": {"username": self.username} }]
return User.objects.aggregate(*pipeline)
def match_test_id(self):
pipeline = [{ "$match": {"id": self.id} }]
return User.objects.aggregate(*pipeline)
mary = User(username="mary")
mary.save()
mary.reload()
agg_username = mary.match_test_username
for doc in agg_username():
print("match_test_username:", doc)
agg_id = mary.match_test_id
for doc in agg_id():
print("match_test_id:", doc)
如果你运行这个,匹配对用户名有效(match_test_username),但我不能让它与主键一起工作,我试过键名:_id , pk, id.
我做错了什么?
有没有关于这个的文档?我只找到了这个:Flask-MongoEngine & PyMongo Aggregation Query 非常有帮助。
还有什么会有所帮助,是否有更好的方法 ("pythonic way") 来迭代调查结果?
提前致谢!
您应该在查询中使用 ObjectId
类型的 ID。所以你应该这样做:
pipeline = [{ "$match": {"_id": ObjectId(self.id)} }]
return User.objects.aggregate(*pipeline)
我正在尝试将聚合与 mongoengine 结合使用。此外,很难找出它是如何工作的(因为文档中没有关于它的任何内容),我取得了一些进展。
但是我无法匹配主键:
from mongoengine import *
connect('test')
class User(Document):
username = StringField()
def match_test_username(self):
pipeline = [{ "$match": {"username": self.username} }]
return User.objects.aggregate(*pipeline)
def match_test_id(self):
pipeline = [{ "$match": {"id": self.id} }]
return User.objects.aggregate(*pipeline)
mary = User(username="mary")
mary.save()
mary.reload()
agg_username = mary.match_test_username
for doc in agg_username():
print("match_test_username:", doc)
agg_id = mary.match_test_id
for doc in agg_id():
print("match_test_id:", doc)
如果你运行这个,匹配对用户名有效(match_test_username),但我不能让它与主键一起工作,我试过键名:_id , pk, id.
我做错了什么?
有没有关于这个的文档?我只找到了这个:Flask-MongoEngine & PyMongo Aggregation Query 非常有帮助。
还有什么会有所帮助,是否有更好的方法 ("pythonic way") 来迭代调查结果?
提前致谢!
您应该在查询中使用 ObjectId
类型的 ID。所以你应该这样做:
pipeline = [{ "$match": {"_id": ObjectId(self.id)} }]
return User.objects.aggregate(*pipeline)