如何从mongodb中的嵌套嵌入式文档查询并返回单个字段?

时间:2015-10-20 16:41:19

标签: mongodb

我正在尝试构建一个动词数据库,其中:

  • 每个动词都有很多结合
  • 每个结合都有一个时态名称(存在,不完美,......)和许多形式
  • 每个表格都有人称代词(io,tu,...)和实际的共轭动词(共轭)

我选择这种结构是因为我想做两种类型的查询:

  1. 给定动词,时态和代词,返回相关的共轭
  2. 给出动词,显示其所有时态,代词和变形
  3. 我正在努力争取第一个。这是我到目前为止(但它不起作用):

    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"}]
                        }
                      ]
                     }])
    

    我愿意更改数据库的结构以便于查询,所以请随意提出更自然的方法。

1 个答案:

答案 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"}