0

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"
                                 }
                        }

1 Answer 1

1

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)))
        );
Sign up to request clarification or add additional context in comments.

2 Comments

you know how can i search in this comment array from php? ex. to return the username
use Comment.username

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.