HintergrundinformationenWie fügt man Informationen zu einem Dokument in Mongo an?
Ich habe folgende Daten in meiner Mongo Datenbank:
{ "_id" :
ObjectId("581c97b573df465d63af53ae"),
"ph" : "+17771111234",
"fax" : false,
"city" : "abd",
"department" : "",
"description" : "a test"
}
ich jetzt schreibe ein Skript, das eine Schleife durch eine CSV-Datei werden die Daten enthält, die ich an die anhängen müssen Dokument. Zum Beispiel könnten die Daten wie folgt aussehen:
+17771111234, 10:15, 12:15, [email protected]
+17771111234, 1:00, 9:00, [email protected]
Letztlich möchte ich mit einem Mongo Dokument am Ende, das wie folgt aussieht:
{ "_id" :
ObjectId("581c97b573df465d63af53ae"),
"ph" : "+17771111234",
"fax" : false,
"city" : "abd",
"department" : "",
"description" : "a test",
"contact_locations": [
{
"stime": "10:15",
"etime": "12:15",
"email": "[email protected]"
},
{
"stime": "1:00",
"etime": "9:00",
"email": "[email protected]"
},
]
}
Problem
Der Code I‘ In der Praxis werden neue Dokumente erstellt, anstatt an die vorhandenen angehängt zu werden. Und tatsächlich erstellt es nicht einmal ein neues Dokument pro Zeile in der CSV-Datei ... was ich noch nicht genug getestet habe, um wirklich zu verstehen warum.
-Code
Für jede Zeile in der CSV-Datei, ich bin mit der folgenden Logik
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));
}
}
Fragen
Gibt es eine Möglichkeit, „anhängen "zu Dokumenten? Oder muss ich das vorhandene Dokument greifen, als ein Array speichern, mein Array von Kontaktstellen mit dem Hauptdokument zusammenführen und dann erneut speichern?
Wie kann ich abfragen, ob das Objekt "contact_locations" bereits in einem Dokument vorhanden ist?