如何定义MongoDB中多个地址的自定义地址类型的架构



对于MongoDB中的多个地址,我们通常将地址存储在数组中。

address:[
{
"type" : "home",
"primary" : false,
                            
"streetaddress" : "Some",
                            
"locality" : "Farnborough",
"region" : "England",
"formatted" : "Farnborough, United Kingdom",
"country" : "United Kingdom",
"location" : [
-0.752615,
51.2868939
]
},
{
"type" : "business",
                        
"locality" : "London",
"region" : "England",
"formatted" : "The Gherkin, London, United Kingdom",
"primary" : false,
"streetaddress" : "30 St Mary Axe",
"country" : "United Kingdom",
"location" : [
-0.08030649999999999,
51.51449179999999
]
}
]

但要通过键获取特定地址。家庭或企业,我们需要循环浏览阵列。除了以下定义以下

以外,还有其他其他方法
{
      home_address:
              {
                "streetaddress" : "Some",
         
                "locality" : "Farnborough",
                "region" : "England",
                "formatted" : "Farnborough, United Kingdom",
                "country" : "United Kingdom",
                "location" : [
                              -0.752615,
                              51.2868939
                             ]
            },
    business_address : {
               "locality" : "London",
               "region" : "England",
               "formatted" : "The Gherkin, London, United Kingdom",
               "primary" : false,
               "streetaddress" : "30 St Mary Axe",
               "country" : "United Kingdom",
               "location" : [
                              -0.08030649999999999,
                              51.51449179999999
                           ],
            },
    primary_address : "home_address"
    }

通常,如果您确切知道自己要查询一个数组的某个值,并且您知道该值,则可以将其变成具有值的子文档作为钥匙。

类似于您上述内容:

"address": {
    "type_home": { "street": ... }, 
    "type_business": {"street": ...},
    "primary": "type_home", 
    "available": ["type_home", "type_business"]
}

灵活的模式是MongoDB功能的一部分,您应该利用它来帮助优化应用程序使用情况。上述模式将有助于比在数组上循环更快地查询特定地址。

看到更多数据模型示例

,您可能会受益

最新更新