Search code examples
phpmongodbjenssegers-mongodb

Calling Mongodb stored functions on an insert in php


I'm using Mongodb 3.2 with PHP in Laravel with Jensseger laravel-mongodb, documentation here: https://github.com/jenssegers/laravel-mongodb

I'm inserting data through this code and it works fine:

$clientes = DB::connection(env('DB_DATABASE'))->collection('catalogo_clientes');
$clientes->insert(array("_id" => "1", "nombre" => "test", "disponible" => 1));

However, I'd like to use a function I created in mongo instead of the "1" in the "_id", when inserting through the command line I'd normally use this, which works fine:

db.loadServerScripts();
db.catalogo_clientes.insert(
    {
        _id: getNextId("clientes"),
        nombre: "Bob X.",
        disponible: 1
    }
)

How can I insert through php into mongo using the same function of "getNextId()"?


Solution

  • This is an example using the Jenssegers' lib:

    $result = DB::collection('YOUR_COLLECTION')->raw(function($collection) use ($folio, $name, $type, $entrega_digital, $motivo_rechazado)
    {
        return $collection->updateOne(
        array('Folio' => (int)$folio, 'documentos_'.$type.'.nombre' => $name),
        array(
            '$set' => array('documentos_'.$type.'.$.entrega_digital' => $entrega_digital, 'documentos_'.$type.'.$.motivo_rechazado' => $motivo_rechazado)
            )
        );
    });
    

    With the cursor you can use all the native methods: https://docs.mongodb.com/manual/