背景信息
我的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));
}
}问题
发布于 2016-11-04 15:02:45
嗨,是的,你能做到的!
首先,您需要找到您的文档并推送所需的新值:
使用findAndModify和$addToSet:
$cursor = $contact_collection->findAndModify(
array("ph" => "+17771111234"),
array('$addToSet' =>
array(
"contact_locations" => array(
"stime"=> "10:15",
"etime"=> "12:15",
"email"=> "test@yahoo.com"
)
)
)
);最好的部分是$addToSet不会添加2次相同的内容,所以您不会有两倍相同的值:)
这里是docs https://docs.mongodb.com/manual/reference/operator/update/addToSet/
https://stackoverflow.com/questions/40425533
复制相似问题