Alexandros
Alexandros

Reputation: 27

Insert array in array at mongodb with php

MongoDB schema:

{
        "_id" : ObjectId("60057ff5c34000008a00214a"),
        "Name" : "Test Store",
        "AFM" : "099360666",
        "DOY" : "ffa",
        "Address" : "faf",
        "TEL" : "sss",
        "Products" : [
                {
                        "_id" : ObjectId("600584b8c34000008a00214d"),
                        "pID" : "099360666/1",
                        "pNAME" : "old scholl 2",
                        "pPRICE" : "55",
                        "pBRAND" : "vans",
                        "pDESCRIPTION" : "eco frinedly",
                        "pSIZE" : "45,44",
                        "pDEPARTMENT" : "Men/Shoes/Trainers",
                        "pTHUMBNAIL" : "http://127.0.0.1/pricedoc/assets/img/products/p1.jpg",
                        "pQUANTITY" : "7",
                        "pCOMMENTS" : {
                                "Comment" : [ ]
                        }
                }
        ],
        "nextProductCounter" : 2
}

I want to add comments through a html form using php to add comment at db. The best I've got is this, but seems to not work

$new_comm = array(
  "username" => "guest",
  "date" =>  new \MongoDB\BSON\UTCDateTime(strtotime(date('d-m-Y 00:00'))),
  "text" => "excellent product", 
  "rating" => "4"
);

        
$collection->updateOne(
  array("Products._id" =>  new MongoDB\BSON\ObjectId("60058012c34000008a00214b")), 
  array('$push' => array("Products.pCOMMENTS" => array("Comment"=>$new_comm)))
        );

Why the pCOMMENTS array isn't updating?

Expected results

                        "pCOMMENTS" : {
                                "Comment" : {
                                   "username" : "guest",
                                   "date" : "18/1/2021",
                                   "text" : "excellent product",
                                   "rating" : "4"
                                 }
                        }

Upvotes: 0

Views: 91

Answers (1)

Gibbs
Gibbs

Reputation: 22956

You need to use positional operator

Reference

$collection->updateOne(
  array("Products._id" =>  new MongoDB\BSON\ObjectId("60058012c34000008a00214b")), 
  array('$push' => array("Products.$.pCOMMENTS" => array("Comment"=>$new_comm)))
        );

Upvotes: 1

Related Questions