michaelpnrs
michaelpnrs

Reputation: 111

Updating and pushing an array to mongo collection

Hello all I am trying to create a query in order to update user's by adding another product in MongoDB.

The structure of the table orders is:

{
  "username": "mike",
  "products": [
    {
      "_id": {
        "$oid": "61f14c42855800006f003062"
      },
      "number": "3",
      "name": "Honduras",
      "price": 7,
      "stock": 10
    }
  ],
  "status": "UNPAID"
}

My query in PHP code is the following:

$collection -> updateOne(
  "username"=>"$username",'$push'=>["products" => "$json"]
);

But I get the same error everytime:

Parse error: syntax error, unexpected token "=>", expecting ")" 

Any suggestions?

Upvotes: 1

Views: 155

Answers (1)

Ande Caleb
Ande Caleb

Reputation: 1204

i use a third party service/library to do that - MongoDBDriverManager PHP library

<?php

    $query = new MongoDBDriverBulkWrite;
    $query->update(
       ['username' => $username],
       ['$set' => ['products' => $json]],
    );

    $db_manager = new MongoDBDriverManager('mongodb://localhost:27017');
    $dbresult= $manager->executeBulkWrite('dbname.orders', $query);

?>

you can get more understanding i get my resources from here..

https://docs.mongodb.com/drivers/php/

Upvotes: 1

Related Questions