我正在尝试构建一个动词数据库,其中:
我选择这种结构是因为我想做两种类型的查询:
我正在努力争取第一个。这是我到目前为止(但它不起作用):
db.verbs.findOne({"verb": "comprare", "conjugations": {"$elemMatch": {"tense": "present", "forms.pronoun": "io"}}}, {"conjugations.forms.conjugation": 1})
这是一个可重复的例子:
db.verbs.insert([{
"verb": "comprare",
"conjugations": [
{
"tense": "present",
"forms": [{"pronoun": "io", "conjugation": "compro"},
{"pronoun": "tu", "conjugation": "compri"}],
},
{
"tense": "imperfect",
"forms": [{"pronoun": "io", "conjugation": "compravo"},
{"pronoun": "tu", "conjugation": "compravi"}]
}
]
},
{
"verb": "bere",
"conjugations": [
{
"tense": "present",
"forms": [{"pronoun": "io", "conjugation": "bevo"},
{"pronoun": "tu", "conjugation": "bevi"}]
},
{
"tense": "imperfect",
"forms": [{"pronoun": "io", "conjugation": "bevevo"},
{"pronoun": "tu", "conjugation": "bevevi"}]
}
]
}])
我愿意更改数据库的结构以便于查询,所以请随意提出更自然的方法。
答案 0 :(得分:1)
您可以使用管道中的聚合框架$unwind
从嵌套数组创建文档。你有两个嵌套数组,所以你将放松两次。
db.verbs.aggregate([
// match documents with specific verb
{$match: {verb: "comprare"}},
// query each conjugation as a separate document
{$unwind: "$conjugations"},
// match conjugations with the provided tense
{$match: {"conjugations.tense": "present"}},
// query each form as a separate document
{$unwind: "$conjugations.forms"},
// match conjugation form with the provided pronoun
{$match: {"conjugations.forms.pronoun": "io"}},
// only select fields of interest
{$project: {"conjugations": 1, _id: 0}}
]);
您可以更改投影以获取特定字段,甚至可以重命名字段并使用表达式:
{"conjugations.forms.pronoun": 1}
-> {conjugations: {forms: {pronoun: "io"}}}
{"conjugation": "$conjugations.forms.conjugation"}
-> {conjugation: "compro"}