mvnobrega's avatar

Relationship in mongodb

Currently I store the relationship id by just passing the related model id, for example:

{ 
   "_id": ObjectId("5ff7fcf93e2c5a4462b1e619"), 
   "text": "This is a comment.", 
   "userId": "5ff7fbc93e2c5a4462b1e612"
} 

However, in some examples or tutorials on the internet I see the relationship like this:

{ 
   "_id": ObjectId("5ff7fcf93e2c5a4462b1e619"), 
   "text": "This is a comment.", 
   "userId": ObjectId("5ff7fbc93e2c5a4462b1e612") 
}

Putting the relationship inside ObjectId("5ff7fbc93e2c5a4462b1e612") or simply the direct id 5ff7fbc93e2c5a4462b1e612 , does it make any difference to query performance?

0 likes
4 replies
mvnobrega's avatar

@jlrdw

Thanks for the help, but I still don't understand, in the post you sent there is this link: https://zappysys.com/blog/ssis-loading-data-into-mongodb-upsert-update-delete-insert/

but it didn't help me understand my situation very well.

In short, I need to know if a mongodb relationship with laravel has better performance with an objectId() key or just with a string.

In short, for each blog article, I have an author, and within the "Article" model I have the author_id:

{ 
   "_id": ObjectId("5ff7fcf93e2c5a4462b1e619"), 
   "text": "This is a comment.", 
   "autor_id": ObjectId("5ff7fbc93e2c5a4462b1e612") 
}

and I consult it like this in Laravel:

my Controller:

$check = Artigo::where('_id', '5ff7fcf93e2c5a4462b1e619')->first();

My model:

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use MongoDB\Laravel\Eloquent\Model;
use MongoDB\Laravel\Relations\HasOne;

class Artigo extends Model
{
    use HasFactory;

    protected $connection = 'mongodb';

    public function redator(): HasOne
    {
        return $this->hasOne(Autor::class, '_id', 'autor_id');
    }

}

get autor:

$teste = Artigo::where('_id', '5ff7fcf93e2c5a4462b1e619')->first();

   dd($teste->redator->autor)
jlrdw's avatar
jlrdw
Best Answer
Level 75

@mvnobrega have you used any of the tools to check query time? I believe debug bar will.

Also see: https://laravel.com/docs/11.x/database#listening-for-query-events

Also depends how you are getting the objectId() key or just with a string.

You'll probably find that there's not a big difference.

Edit:

Their docs uses ObjectId. https://www.mongodb.com/docs/manual/reference/database-references/

So test speed, but following the docs is also a good idea.

1 like
Tray2's avatar

Relational data should always use a Relational databas, and I would 99% of the time it is relational data that you store in any kind of application.

1 like

Please or to participate in this conversation.