Greetings All,
I am using the latest version of MongoDB 6.0.5 Community version on a standalone server and I’m using the latest version of the PHP MongoDB Driver library (mongodb/mongodb - Packagist) to interact with the database.
I have a collection of documents that resemble the following example:
{
"_id": {
"$oid": "644377c8bda636ff6f04ceb2"
},
"acct_id": {
"$oid": "6427eead36cef4611c0ab772"
},
"co_contacts": [
{
"con_id": "000000001",
"con_type": "address",
"con_label": "Main Office",
"con_add1": "51 Maple Dr",
"con_city": "Somewhere",
"con_state": "FL",
"con_zip": "12323",
"con_country": "United States"
},
{
"con_id": "000000002",
"con_type": "address",
"con_label": "2nd Office",
"con_add1": "123 First St.",
"con_city": "Kansas City",
"con_state": "KS",
"con_zip": "13222",
"con_country": "United States"
},
{
"con_id": "000000003",
"con_type": "person",
"con_label": "Manager",
"con_fname": "Bob",
"con_lname": "Smith",
"con_person_num": "232 2212 222",
"con_person_email": "bobs@example.com"
}
],
"co_name": "Big Sky Co",
"co_size": "small",
}
I would like to be able to either update or insert (upsert) documents into the co_contacts array with one call to the database, but I can’t seem to get it right. My workaround is to use two calls as follows:
<?php
$updateResult = $collection->findOneAndUpdate(['_id' => $oid, 'co_contacts.con_id' => '00000002'],['$set' => ['co_contacts.$' => $data]],['returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER]);
if (is_null($updateResult)) $updateResult = $collection->updateOne(['_id' => $oid],['$push' => ['co_contacts' => $data]]);
Can someone help me optimize my PHP code into one call (e.g. upsert)?
Thanks in advance,
Alec