嵌套文档作为对象而不是数组插入

时间:2019-02-13 18:41:53

标签: php mongodb

我目前正在将一个我正在处理的站点从MySQL迁移到MongoDB,并且遇到了一个奇怪的问题。

我正在尝试进行以下收藏:

country (string)
regions (array)
    regions (string)
    cities (array)
        city (string)

问题是由于某种原因,city数组之一正在作为对象插入。一切都来自相同的来源,并使用相同的代码。

问题示例:

[
    {
        country: "United States",
        regions: (array) [
            {
                region: "Arizona",
                cities: (array) [
                    { city: "Phoenix" }
                ]
            },
            {
                region: "California",
                cities: (object) [
                    { city: "Los Angeles" }
                ]
            }
        ]
    }
]

这是一个问题,因为当我搜索{ "regions.cities.city": "Los Angeles" }时,结果返回为空,但是如果我搜索{ "regions.cities.city": "Phoenix" },则会得到正确的结果。

我希望这一切都说得通,但请随时提出问题。

-编辑-

PHP代码产生问题:

$countries = $this->db_model->find_list('countries', array(), false, true);
foreach($countries as $key => $country)
{
    if($regions = $this->db_model->find_list('regions', array('country_id' => $country['id']), false, true))
    {
        foreach($regions as $rkey => $region)
        {
            if($cities = $this->db_model->find_list('cities', array('region_id' => $region['id']), false, true))
            {
                $regions[$rkey]['cities'] = $cities;
            }
        }
        $countries[$key]['regions'] = $regions;
    }
}
$this->mongo->batch_insert('countries', $countries);

1 个答案:

答案 0 :(得分:3)

原来需要重置的阵列键的作用是,我删除了一些符合某些条件的项目(从示例代码中删除,以使内容易于阅读,将包含在下面的代码中)。

$countries = $this->db_model->find_list('countries', array(), false, true);
foreach($countries as $key => $country)
{
    if($country['deleted']) { unset($countries[$key]); }
    elseif($regions = $this->db_model->find_list('regions', array('country_id' => $country['id']), false, true))
    {
        foreach($regions as $rkey => $region)
        {
            if($region['deleted']) { unset($regions[$rkey]); }
            elseif($cities = $this->db_model->find_list('cities', array('region_id' => $region['id']), false, true))
            {
                foreach($cities as $ckey => $city)
                {
                    if($city['deleted']) { unset($cities[$ckey]); }
                }
                $regions[$rkey]['cities'] =array_values($cities);
            }
        }
        $countries[$key]['regions'] = array_values($regions);
    }
}
$this->mongo->batch_insert('countries', array_values($countries));

谢谢Marco提供的所有帮助和见识。