Reputation: 2031
I have this document:
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
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
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