PHP code example of phalcon / incubator-mongodb

1. Go to this page and download the library: Download phalcon/incubator-mongodb library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

phalcon / incubator-mongodb example snippets


use Phalcon\Incubator\MongoDB\Mvc\Collection\Manager;

$di->set(
    'collectionsManager',
    function () {
        return new Manager();
    }
);

use Phalcon\Incubator\MongoDB\Mvc\Collection;

class RobotsCollection extends Collection
{
    public $code;

    public $theName;

    public $theType;

    public $theYear;
}

$robots = new RobotsCollection($data);

use MongoDB\BSON\ObjectId;

// How many robots are there?
$robots = RobotsCollection::find();

echo "There are ", count($robots), "\n";

// How many mechanical robots are there?
$robots = RobotsCollection::find([
    [
        "type" => "mechanical",
    ],
]);

echo "There are ", count(robots), "\n";

// Get and print virtual robots ordered by name
$robots = RobotsCollection::findFirst([
    [
        "type" => "virtual",
    ],
    "order" => [
        "name" => 1,
    ],
]);

foreach ($robots as $robot) {
    echo $robot->name, "\n";
}

// Get first 100 virtual robots ordered by name
$robots = RobotsCollection::find([
    [
        "type" => "virtual",
    ],
    "order" => [
        "name" => 1,
    ],
    "limit" => 100,
]);

foreach (RobotsCollection as $robot) {
    echo $robot->name, "\n";
}

$robot = RobotsCollection::findFirst([
    [
        "_id" => new ObjectId("45cbc4a0e4123f6920000002"),
    ],
]);

// Find robot by using \MongoDB\BSON\ObjectId object
$robot = RobotsCollection::findById(
    new ObjectId("545eb081631d16153a293a66")
);

// Find robot by using id as sting
$robot = RobotsCollection::findById("45cbc4a0e4123f6920000002");

// Validate input
if ($robot = RobotsCollection::findById($_POST["id"])) {
    // ...
}

use Phalcon\Incubator\MongoDB\Mvc\Collection;
use Phalcon\Incubator\MongoDB\Mvc\Collection\Behavior\Timestampable;

class RobotsCollection extends Collection
{
    public $code;

    public $theName;

    public $theType;

    public $theYear;
    
    protected function onConstruct()
    {
         $this->addBehavior(
             new Timestampable(
                 [
                     "beforeCreate" => [
                         "field"  => "created_at",
                         "format" => "Y-m-d",
                     ],
                 ]
             )
         );
    }
}