0
如何在_id = 4ef1fddbb33c45091d000000部分中使用ID = 1的主題獲取所有消息?如何在MongoDB(MongoEngine)中執行此簡單查詢?
我有一些模型:
class Message(EmbeddedDocument):
id = SequenceField(unique=True)
content = StringField()
create_date = DateTimeField()
user = StringField()
active = BooleanField()
class Theme(EmbeddedDocument):
id = SequenceField(unique=True)
title = StringField()
content = StringField()
create_date = DateTimeField()
user = StringField()
messages = ListField(EmbeddedDocumentField(Message))
active = BooleanField()
class Section(Document):
title = StringField(unique=True)
description = StringField()
themes = ListField(EmbeddedDocumentField(Theme))
而這一模式產生一些JSON,像這樣:
{
"_cls": "Section",
"_id": {
"$oid": "4ef1fddbb33c45091d000000"
},
"_types": [
"Section"
],
"description": "Test description",
"themes": [
{
"_types": [
"Theme"
],
"title": "Test",
"messages": [
{
"content": "I'm content!",
"_types": [
"Message"
],
"id": 12,
"_cls": "Message"
},
{
"content": "I'm second message!",
"_types": [
"Message"
],
"_cls": "Message",
"user": "inlanger",
"id": 13
}
],
"content": "Test description",
"_cls": "Theme",
"id": 1
},
{
"_types": [
"Theme"
],
"title": "Test2",
"messages": [
{
"_types": [
"Message"
],
"create_date": {
"$date": "2012-01-31T11:29:17.120Z"
},
"content": "Some message",
"_cls": "Message",
"id": 14,
"user": "inlanger"
}
],
"content": "Test description 2",
"_cls": "Theme",
"id": 2
},
{
"_types": [
"Theme"
],
"create_date": {
"$date": "2012-01-31T12:00:50.889Z"
},
"title": "Ататата",
"messages": [],
"content": "Theme number 3",
"user": "inlanger",
"id": 15,
"_cls": "Theme"
}
],
"title": "Test"
}
我使用一些代碼...它工作的,但它的醜陋:
def get_theme_messages(section_id, theme_id, page = 1):
section = Section.objects(id = section_id, themes__id = theme_id).first()
for theme in section.themes:
if theme.id == int(theme_id):
return theme.messages
break
else:
pass
+1你可以限制你到達頂級域從文檔返回(即僅檢索消息),但在這種情況下這沒有多大幫助。編輯:沒關係,我發現那不是頂級的領域。 – 2012-01-31 18:11:47
如果我有成千上萬的記錄這一切都正常嗎? – inlanger 2012-01-31 18:14:48
如果你有成千上萬的'EmbeddedDocument',是的。如果您返回的是比您最終需要的更多頂級「文檔」,則可以隨時過濾查詢。 – dcrosta 2012-01-31 19:33:41