MongoDB: How to execute multiple dereferences in a query?

  mongodb, question

I set up several sets,Country,Province,City,Univ.

Country and provision, provision and city, city and univ are all one-to-many relationships. Connect by reference.

Now I want to know which univ is in a country and how to do this? Suppose the country is country0.

The document structure is as follows:

{
 _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"}
 }

I looked for some information, if there is only one country and the references involved are not more than two levels, it can be usedFetch () function. But there are at least three floors here.

I also saw that when someone introduced the quotation, he said it could be used.Python driverHowever, it is not good to record query performance when using python driver.

My own thinking is:

  1. Gets all providers belonging to country0.
  2. Gets all cities that belong to the provision in 1.
  3. Finally, all univ in city are obtained.

However, there are too many commands involved, which is cumbersome.

Because the city/provision/country of the university is very unlikely to change, the correct solution is to add these fields to the university’s documents and index them.

{
_id:”univ0″,
location: { city: { }, province: {}, country: {} }
}

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

You can choose to use DBRef or directly deposit the name of city/provision/country.