PHP : Push an object in deep nested array

Hello,

I have this document :

{
“_id”: “670cd1fafeb0a1ef44162a65”,
“post_id”: “9”,
“comments”: [
{
“_id”: “6717e0c7e074859fa50a75f3”,
“author_id”: “3”,
“comment_text”: “Hello”,
“replies”: [
{
“_id”: “67181338e074859fa50a7620”,
“author_id”: “9”,
“replies”: [ !!! INSERT THE ARRAY HERE !!! ]
}
]
}
]
}

I’m trying to insert this array WHERE “_id”: “67181338e074859fa50a7620” :

$array = array (
‘_id’ => new MongoDB\BSON\ObjectId(),
‘author_id’ => $_SESSION[‘userid’],
‘comment_text’ => ‘How are you’,
‘replies’ => array()
);

I Tried this but to no avail :

$updateResult = $db->updateOne(
[‘post_id’ => ‘9’, ‘comments.replies._id’ => new \MongoDB\BSON\ObjectID(‘67181338e074859fa50a7620’)], [‘$push’ => array(‘comments.replies.$.replies’ => $array)]
);

I tried also to use arrayFilters but I got it wrong too.

Thank you for your help,
Chuck

Hi Chuck,

Not a PHP expert (yet :stuck_out_tongue_winking_eye:) so forgive me if I am misunderstanding your question.
You have a collection of documents that represent posts in your system and each one of them contains an array of comments. You are trying to add a new comment to an already existing post. You are using the right method but it needs two arguments: one to indicate the document you want to update, and another with the expected update.`

$updateResult = $collection->updateOne(
    ['_id' => '67181338e074859fa50a7620'],
    ['$push' => $array]
  );

I cannot test this code at the moment, but with the mercy of the syntax gods, it should at least help you understand what was the problem with your code.
As an aside, I would suggest not using an Id for each of the comments, since they are embedded objects accessed via the main document.
Hope this helps.
Jorge

Hello,
thank your for answering me.

I can’t make your code work.

I can’t select directly the nested ObjectID like you suggest :

['_id' => '67181338e074859fa50a7620']

I can only select it like that :

['comments.replies._id' => '67181338e074859fa50a7620']

But after that, I can’t find the right path to push my array in the “replies” key that match this objectID.