Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

176
Visualizações
How do I add a document to existing filled collection?

I am building an eShop for educational purposes and I need to handle the orders from a user. A user has a basket which is getting filled with products. If he decides buy another product I have insert a document into the existing collection of the card

Current MongoDB collection:

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

By adding another product, needs to be inserted in the existing collection in the field of products.

Expected to look like:

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

I am using PHP for the back end operations. The script that I wrote it is simple. I am searching if orders with user's username exist. If they exist then I lock the current order and make the operations needed.

I think that I am missing something in syntax of the update for the purpose described above:

PHP script:

if (isset($_POST['add'])){
            // Ordered by name from URL
            $username = $_GET['username'];
            // Product info
            $name = $_POST['add'];

            // Finds the product selected from products
            $product = $collection -> findOne(array("name" => "$name"));
            // Serialize product to be added.
            $json = MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($product));

            // Searching for order from certain user
            $collection = $db -> orders;
            $exists = $collection -> findOne(array("username" => "$username"));
            
            if (!is_null($exists)){
                // The problem is here (maybe?)
                $exists->updateOne(
                    array("products" => {}),array('$set'=>$json);
                );
            }

Any help and suggestions would be really appreciated!

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Well, you need to use something like below

db.collection.update(
 {find Condition}, 
 {$push: {products : {key: value, key2: value 2}}
)

Here the catch is push. It adds an element to array. Here the element is an object.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda