Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda