Happydevdays Happydevdays - 28 days ago 5
PHP Question

how to append information to a document in mongo?

Background Information

I have the following data in my mongo database:

{ "_id" :
ObjectId("581c97b573df465d63af53ae"),
"ph" : "+17771111234",
"fax" : false,
"city" : "abd",
"department" : "",
"description" : "a test"
}


I am now writing a script that will loop through a CSV file that contains data that I need to append to the document. For example, the data might look like this:

+17771111234, 10:15, 12:15, test@yahoo.com
+17771111234, 1:00, 9:00, anothertest@yahoo.com


Ultimately I want to end up with a mongo document that looks like this:

{ "_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"
},
]
}


Problem

The code I've written is actually creating new documents instead of appending to the existing ones. And actually, it's not even creating a new document per row in the CSV file... which I haven't debugged enough yet to really understand why.

Code

For each row in the csv file, I'm running the following logic

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));
}
}


Questions


  1. Is there a way to "append" to documents? Or do I need to grab the existing document, save as an array, merge my contact locations array with the main document and then resave?

  2. how can I query to see if the "contact_locations" object already exists inside a document?


Answer

Hi yes you can do it !

1st you need to find your document and push the new value you need :

use findAndModify and $addToSet :

$cursor = $contact_collection->findAndModify(
     array("ph" => "+17771111234"),
     array('$addToSet' => 
        array(
            "contact_locations" => array(
                 "stime"=> "10:15", 
                 "etime"=> "12:15", 
                 "email"=> "test@yahoo.com"
            )
        )
     )
);

The best part is $addToSet wont add 2 time the same stuff so you will not have twice the same value :)

Here the docs https://docs.mongodb.com/manual/reference/operator/update/addToSet/

Comments