Shibbir
Shibbir

Reputation: 2031

laravel / Mongodb - How to insert new key/ value to an existing document

I have this document:

enter image description here

Now I want to add a new key / value to that document which id is : 34401

My key / value is like an array:

$data = [
    'id_project'            =>  $id_project, 
    'id_product'            =>  $product_id, 
    'link'                  =>  $link, 
    'id_product_competitor' =>  $id_competitor, 
    'link_competitor'       =>  ''
];

what I am doing is this:

$insert_to_mongodb = DB::connection('mongodb')
->collection( 'products_' . $id_project . '_' . $id_competitor )                
->insert($data);

Here this 'products_' . $id_project . '_' . $id_competitor is products_1_23 as collection name.

After run this code Its inserting newly document but I want to add ths key/value to an existing document.

Upvotes: 0

Views: 656

Answers (2)

Jeybin George
Jeybin George

Reputation: 458

I belive the better way is to create a model for the mongodb collection, install Jenssegers\Mongodb using the command composer require jenssegers/mongodb, reference link

<?php 

namespace App\Models;

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class ProductsModel extends Eloquent{

    /**
     * Connection name
     *
     */
    protected $connection   =   'mongodb';

    /**
     * Collection name
     * 
     */
    protected $collection   =   'products';


}

Now you can insert or update using the eloquent way

 ProductsModel::insert($data);

 ProductsModel::where('_id',$id)->update($data);

Upvotes: 1

Shibbir
Shibbir

Reputation: 2031

Well, I have soleve it by following way:

$insert_to_mongodb = DB::connection('mongodb')
->collection( 'products_' . $id_project . '_' . $id_competitor )
->where('id', (int) $product_id)
->update($data, ['upsert' => true]);

Upvotes: 0

Related Questions