【发布时间】:2016-11-04 23:07:15
【问题描述】:
背景信息
我的 mongo 数据库中有以下数据:
{ "_id" :
ObjectId("581c97b573df465d63af53ae"),
"ph" : "+17771111234",
"fax" : false,
"city" : "abd",
"department" : "",
"description" : "a test"
}
我现在正在编写一个脚本,它将遍历一个包含我需要附加到文档的数据的 CSV 文件。例如,数据可能如下所示:
+17771111234, 10:15, 12:15, test@yahoo.com
+17771111234, 1:00, 9:00, anothertest@yahoo.com
最终我想得到一个如下所示的 mongo 文档:
{ "_id" :
ObjectId("581c97b573df465d63af53ae"),
"ph" : "+17771111234",
"fax" : false,
"city" : "abd",
"department" : "",
"description" : "a test",
"contact_locations": [
{
"stime": "10:15",
"etime": "12:15",
"email": "test@yahoo.com"
},
{
"stime": "1:00",
"etime": "9:00",
"email": "anothertest@yahoo.com"
},
]
}
问题
我编写的代码实际上是创建新文档而不是附加到现有文档。实际上,它甚至没有在 CSV 文件中的每行创建一个新文档……我还没有调试到足够多的时间来真正理解为什么。
代码
对于 csv 文件中的每一行,我正在运行以下逻辑
while(!$csv->eof() && ($row = $csv->fgetcsv()) && $row[0] !== null) {
//code that massages the $row into the way I need it to look.
$data_to_submit = array('contact_locations' => $row);
echo "proving that the record already exists...: <BR>";
$cursor = $contact_collection->find(array('phnum'=>$row[0]));
var_dump(iterator_to_array($cursor));
echo "now attempting to update it....<BR>";
// $cursor = $contact_collection->update(array('phnum'=>$row[0]), $data_to_submit, array('upsert'=>true));
$cursor = $contact_collection->insert(array('phnum'=>$row[0]), $data_to_submit);
echo "AFTER UPDATE <BR><BR>";
$cursor = $contact_collection->find(array('phnum'=>$row[0]));
var_dump(iterator_to_array($cursor));
}
}
问题
有没有办法“附加”到文档中?还是我需要抓取现有文档,保存为数组,将我的联系人位置数组与主文档合并,然后重新保存?
如何查询“contact_locations”对象是否已存在于文档中?
【问题讨论】: