skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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]);
    

  2. I belive the better way is to create a model for the mongodb collection,
    install JenssegersMongodb using the command composer require jenssegers/mongodb, reference link

    <?php 
    
    namespace AppModels;
    
    use JenssegersMongodbEloquentModel 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search