如何为mongodb中的多个地址定义自定义地址类型的模式

时间:2017-03-09 13:58:38

标签: mongodb schema

对于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"

    }

1 个答案:

答案 0 :(得分:0)

通常,如果您确切地知道您要查询某个数组的某个值并且您知道所述值,则最好将其转换为以该值为键的子文档。

与上面的相似:

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

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

您可能会从更多data models examples

中受益