search

Home  >  Q&A  >  body text

MongoDB:怎样在一次查询中执行多次解引用?

我设定了几个集合,Country, Province, City, Univ.

country和province,province和city,city和univ之间都是一对多的关系。通过引用连接。

现在我想知道,一个country中有哪些univ,这个要怎么做?假设该country为country0.

文档结构如下:

{
    _id:"country0",
    provinces:[
    {
        $ref:"Province",
        $id:"province0"
    },
    ...
    ] 
}

{
    _id:"province0",
    belongs:{$ref:"Country", $id:"country0"},
    cities:[
    {
        $ref:"City",
        $id:"city0"
    }
    ...
    ]
}

{
    _id:"city0",
    belongsTo:{$ref:"Province",$id:"province0"},
    univs:[
    {
        $ref:"Univ",
        $id:"univ0"
    }
    ...
    ]
}

{
    _id:"univ0",
    address:{$ref:"City", $id:"city0"}
}

我找过一些资料,如果country只有一个,并且涉及到的引用不超过两层,可以用fetch()函数。但是这里至少有3层了。

也看到有人介绍引用的时候说可以用python驱动,但是用python驱动的话,就不好记录查询性能了。

我自己的思路是:

  1. 获取所有属于country0的province.
  2. 获取所有属于1中province的city。
  3. 最后获得city中的所有univ。

但是涉及到的命令太多了,显得繁琐

怪我咯怪我咯2802 days ago643

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-04-24 09:12:28

    Because the city/province/country of the university is rarely likely to change, the correct solution is to add these fields to the university document and index it.

    {
    _id:"univ0",
    location: { city: { }, province: {}, country: {} }
    }

    db.university.ensureIndex({"location.country":1});

    You can choose to use DBRef or directly save the name of city/province/country.

    reply
    0
  • Cancelreply