【问题标题】:Greater than (gte) query in MongoEngine for EmbeddedDocumentListFieldMongoEngine 中针对 EmbeddedDocumentListField 的大于 (gte) 查询
【发布时间】:2026-02-06 14:10:01
【问题描述】:

这就是我的模型的样子。 A 类的 EmbeddedDocumentListField 为 SlotTime。

class SlotTime(EmbeddedDocument):
    # this is having minutes like 780 for 1pm.
    start_time = IntField(required=True)
    end_time = IntField(required=True)

 class A(Document):
    name = StringField(primary_key=True)
    slot_hours = EmbeddedDocumentListField(SlotTime)

SlotTime 有一个包含开始和结束时间值的对象列表。 [<SlotTime: SlotTime object>,<SlotTime: SlotTime object>] 现在我想进行一个查询,它将返回 start_time 大于给定值的结果。 想要一个类似于这个查询的东西:A.objects.get(name__exact='xyz').slot_hours.filter(start_time__gte=780)

试过了,但这会返回所有值。 A.objects.filter(name__exact='xyz',slot_hours__start_time__gte=780)[0].slot_hours

有人可以帮助我如何做到这一点吗?谢谢!

【问题讨论】:

标签: django python-2.7 mongoengine


【解决方案1】:

假设你有你提供的模式,你可以简单地使用__gte 操作符来实现。见下文:

A.objects(name__exact='xyz', slot_hours__start_time__gte=780)
A.objects(name__exact='xyz').filter(slot_hours__start_time__gte=780)

【讨论】:

    【解决方案2】:

    我认为 MongoEngine 目前不支持进一步过滤使用您上面使用的 .filter() 查询收到的 EmbeddedDocuments。这就是为什么访问slot_hours 会返回该对象的所有SlotTime 对象,而不是只返回start_time 大于780 的那些SlotTime 对象。

    为此,您必须使用列表推导手动过滤掉对象。

    # perform filtering and get the first 'A' object
    obj = A.objects.filter(name__exact='xyz',slot_hours__start_time__gte=780)[0]
    
    # get the relavent 'SlotTime' objects
    slot_time_objs = [x for x in obj.slot_hours if x.start_time >= 780] 
    

    【讨论】:

    • 已经做了这个变通办法,但我不确定是否可以通过查询来实现。
    • 恐怕目前在 MongoEngine 中是不可能的。