Latest

Thursday, July 6, 2017

How to embed object document inside a document in mongodb laravel?

Asked by: Hari


I'm trying to embed a sub document inside a document. But it is inserting as array. This is the way I tried.

    $imei = dechex('03333333333333333');
    $prefix = '000000000000000';
    $imei = substr($prefix, 0, 24 - strlen($imei)).$imei;

    $device = new DeviceModel;
    $device->_id = $imei;
    $device->save();

    $data = new DataLog();

    $data->speed = "50";
    $data->lat = "17.1111";
    $data->lng = "78.2222";

    $device = DeviceModel::first();

    $data = $device->dataLog()->save($data);


    //output
    {
        "_id" : ObjectId("000000000000123456abcdef"),
        "updated_at" : ISODate("2017-07-06T08:31:27.000Z"),
        "created_at" : ISODate("2017-07-06T08:31:27.000Z"),
        "dataLog" : [ 
            {
                "speed" : "78.2222",
                "lat" : "17.1111",
                "updated_at" : ISODate("2017-07-06T08:31:27.000Z"),
                "created_at" : ISODate("2017-07-06T08:31:27.000Z"),
                "_id" : ObjectId("595df55f8f4659124e782d02")
            }
        ]
    }

    // But I want below structure
    //expected output
    {
        "_id" : ObjectId("000000000000123456abcdef"),
        "updated_at" : ISODate("2017-07-06T08:31:27.000Z"),
        "created_at" : ISODate("2017-07-06T08:31:27.000Z"),
        "dataLog" : { 
            "1": {
                "speed" : "78.2222",
                "lat" : "17.1111",
                "updated_at" : ISODate("2017-07-06T08:31:27.000Z"),
                "created_at" : ISODate("2017-07-06T08:31:27.000Z"),
                "_id" : ObjectId("595df55f8f4659124e782d02")
             }
            "2": {
                "speed" : "78.2222",
                "lat" : "17.1111",
                "updated_at" : ISODate("2017-07-06T08:31:27.000Z"),
                "created_at" : ISODate("2017-07-06T08:31:27.000Z"),
                "_id" : ObjectId("595df55f8f4659124e782d02")
             }
        }
    }

I'm using jessenger's mongodb driver and laravel framework. I have created Device Model and DataLog Model.

<?php

namespace App\Models;

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class DeviceModel extends Eloquent
{
    protected $collection = 'devices_collection';

    public function dataLog()
    {
        return $this->embedsMany('App\Models\DataLog');
    }
}


//datalog model
<?php

namespace App\Models;

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class DataLog extends Eloquent
{
    protected $collection = 'devices_collection';
}

The document provided in github jessenger mongodb is not clear and sufficient. I don't understand how to achieve my requirement.



Source

No comments:

Post a Comment

Adbox